-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathAdd One Row To Tree
53 lines (52 loc) · 1.23 KB
/
Add One Row To Tree
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if(depth==1)
{
TreeNode* curr1=new TreeNode (val);
curr1->left=root;
return curr1;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
depth--;
if(depth==1)
{
while(!q.empty())
{
TreeNode* a,*c;
TreeNode* b=q.front();
q.pop();
a=b->left;
b->left=new TreeNode (val);
b->left->left=a;
c=b->right;
b->right=new TreeNode (val);
b->right->right=c;
}
}
int count=q.size();
for(int i=0;i<count;i++)
{
TreeNode* curr3=q.front();
q.pop();
if(curr3->left!=NULL) q.push(curr3->left);
if(curr3->right!=NULL) q.push(curr3->right);
}
}
return root;
}
};