-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddOneRowToTree.py
More file actions
40 lines (39 loc) · 1.12 KB
/
Copy pathAddOneRowToTree.py
File metadata and controls
40 lines (39 loc) · 1.12 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
/**
* 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 v, int d) {
if (d == 1) {
TreeNode* newroot = new TreeNode(v);
newroot->left = root;
return newroot;
}
else if (d == 0) {
TreeNaode* newroot = new TreeNode(v);
newroot->right = root;
return newroot;
}
if (!root) {
return nullptr;
}
else if (d == 2) {
root->left = addOneRow(root->left, v, 1);
root->right = addOneRow(root->right, v, 0);
return root;
}
else if (d > 2) {
root->left = addOneRow(root->left, v, d - 1);
root->right = addOneRow(root->right, v, d - 1);
}
return root;
}
};