-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0623.AddOneRowToTree.cpp
More file actions
47 lines (43 loc) · 1.1 KB
/
0623.AddOneRowToTree.cpp
File metadata and controls
47 lines (43 loc) · 1.1 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
47
/**
* 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:
void addRow(TreeNode* root, const int val, const int depth) {
// Ignore invalid node.
if (root == nullptr) return;
if (depth > 1) {
// Recurse down.
addRow(root->left, val, depth - 1);
addRow(root->right, val, depth - 1);
return;
}
// Insert left.
TreeNode* newLeft = new TreeNode(val);
newLeft->left = root->left;
root->left = newLeft;
// Insert right.
TreeNode* newRight = new TreeNode(val);
newRight->right = root->right;
root->right = newRight;
}
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if (depth == 1) {
// Edge case.
TreeNode* newRoot = new TreeNode(val);
newRoot->left = root;
root = newRoot;
} else {
addRow(root, val, depth - 1);
}
return root;
}
};