-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathAdd One Row to Tree.cpp
66 lines (36 loc) · 1.31 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
55
56
57
58
59
60
61
62
63
64
65
66
/**
* 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 {
void dfs(TreeNode* root, int val, int depth,int lvl){
if(root==nullptr)
return ;
if(lvl==depth-1)
{
TreeNode *n1= new TreeNode(val,root->left,nullptr);
TreeNode *n2= new TreeNode(val,nullptr,root->right);
root->left=n1;
root->right=n2;
return ;
}
dfs(root->left,val,depth,lvl+1);
dfs(root->right,val,depth,lvl+1);
}
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if(depth==1){
TreeNode *n1= new TreeNode(val,root,nullptr);
return n1;
}
dfs(root,val,depth,1);
return root;
}
};