-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathadd_one_row_to_tree.cpp
54 lines (51 loc) · 1.54 KB
/
add_one_row_to_tree.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
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if(depth == 1){
TreeNode* cur = new TreeNode(val);
cur->left = root;
return cur;
}
queue<TreeNode*>q;
q.push(root);
int level = 1;
bool done = false;
while(!q.empty()){
int n = q.size();
cout<<n;
while(n--){
TreeNode* cur = q.front();
cout<<cur->val;
q.pop();
if(level == depth-1){
//add
if(cur->left){
TreeNode* l = cur->left;
cur->left = new TreeNode(val);
cur->left->left = l;
}else{
cur->left = new TreeNode(val);
}
if(cur->right){
TreeNode* r = cur->right;
cur->right = new TreeNode(val);
cur->right->right = r;
}else{
cur->right = new TreeNode(val);
}
done = true;
}else{
if(cur->left != NULL){
q.push(cur->left);
}
if(cur->right != NULL){
q.push(cur->right);
}
}
}
level++;
if(done) break;
}
return root;
}
};