forked from Amitshu2003/All-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_One_Row_to_Tree.cpp
More file actions
46 lines (38 loc) · 1.14 KB
/
Add_One_Row_to_Tree.cpp
File metadata and controls
46 lines (38 loc) · 1.14 KB
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
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth)
{
if(depth == 1)
{
TreeNode *newRoot = new TreeNode(val, root, NULL);
return newRoot;
}
queue<TreeNode*> q;
int curDepth = 1;
q.push(root);
while(q.size() > 0)
{
int qSize = q.size();
while(qSize--)
{
TreeNode *top = q.front();
q.pop();
if(curDepth == depth - 1)
{
TreeNode *leftSubTree = top->left;
TreeNode *rightSubTree = top->right;
TreeNode *newNodeLeft = new TreeNode(val, leftSubTree, NULL);
TreeNode *newNodeRight = new TreeNode(val, NULL, rightSubTree);
top->left = newNodeLeft;
top->right = newNodeRight;
}
if(top->left)
q.push(top->left);
if(top->right)
q.push(top->right);
}
curDepth++;
}
return root;
}
};