-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeRepresentation.cpp
63 lines (51 loc) · 1.47 KB
/
BinaryTreeRepresentation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
You are given an array nodes. It contains 7 integers, which represents the value of nodes of the binary tree in level order traversal. You are also given a root of the tree which has a value equal to nodes[0].
Your task to construct a binary tree by creating nodes for the remaining 6 nodes.
Example:
Input:
nodes = [1 2 3 4 5 6 7]
Output:
1
/ \
2 3
/ \ / \
4 5 6 7
Explanation:
The 7 node binary tree is represented above.
Your Task:
Complete the function void create_tree(node* root0, vector &vec), which takes a root of a Binary tree and vector array vec containing the values of nodes.
Expected Time Complexity: O(1).
Expected Auxiliary Space: O(1).
Constraints:
vec.length = 7
1<=vec[i]<=100
*/
/// Queue based
//User function Template for C++
/*struct node {
int data;
struct node *left;
struct node *right;
};
struct node *newNode(int data) {
struct node *node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}*/
class Solution{
public:
void create_tree(node* root0, vector<int> &vec){
queue<node*> q;
q.push(root0);
for(int i=1;i<vec.size();i+=2){
auto it = q.front();
q.pop();
it->left=newNode(vec[i]);
q.push(it->left);
it->right=newNode(vec[i+1]);
q.push(it->right);
}
}
};