-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path623. Add One Row to Tree.cpp
63 lines (63 loc) · 1.75 KB
/
623. 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
55
56
57
58
59
60
61
62
63
/**
* 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 (root == NULL)
return nullptr;
if (depth == 1)
{
TreeNode *temp = new TreeNode(val);
temp->left = root;
return temp;
}
int level = 1;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
if (level == depth - 1)
{
int sz = q.size();
while (sz--)
{
TreeNode *frnt = q.front();
q.pop();
TreeNode *leftchild = frnt->left;
TreeNode *rightchild = frnt->right;
frnt->left = new TreeNode(val);
frnt->right = new TreeNode(val);
frnt->right->right = rightchild;
frnt->left->left = leftchild;
}
break;
}
else
{
int sz = q.size();
while (sz--)
{
TreeNode *frnt = q.front();
q.pop();
if (frnt->left)
q.push(frnt->left);
if (frnt->right)
q.push(frnt->right);
}
level++;
}
}
return root;
}
};