|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * struct TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode *left; |
| 6 | + * TreeNode *right; |
| 7 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 8 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 10 | + * }; |
| 11 | + */ |
| 12 | +class Solution { |
| 13 | +public: |
| 14 | + void addOneRowRecursive(TreeNode* root, int v, int depth, int current_depth) { |
| 15 | + if(!root) return; |
| 16 | + |
| 17 | + if(current_depth == depth) { //breaking condition |
| 18 | + TreeNode *subLeft = root->left; //store the current left |
| 19 | + root->left = new TreeNode(v); //add new nodes with value = v at current_depth |
| 20 | + root->left->left = subLeft; //attach previous left to left of new root->left |
| 21 | + |
| 22 | + TreeNode *subRight = root->right; |
| 23 | + root->right = new TreeNode(v); |
| 24 | + root->right->right = subRight; |
| 25 | + return; |
| 26 | + } |
| 27 | + addOneRowRecursive(root->left, v, depth, current_depth + 1); |
| 28 | + addOneRowRecursive(root->right, v, depth, current_depth + 1); |
| 29 | + } |
| 30 | + |
| 31 | + TreeNode* addOneRow(TreeNode* root, int v, int d) { |
| 32 | + if (d == 1) { //depth == 1, detach current root, add new root and add the older tree to the left of new root |
| 33 | + TreeNode *newRoot = new TreeNode(v); |
| 34 | + newRoot->left = root; |
| 35 | + return newRoot; |
| 36 | + } |
| 37 | + addOneRowRecursive(root, v, d, 2); |
| 38 | + return root; |
| 39 | + } |
| 40 | +}; |
0 commit comments