[LeetCode] Add One Row to Tree

623. Add One Row to Tree

Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N’s left subtree root and right subtree root. And N’s original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root’s left subtree.

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 {
private:
void rebalance(TreeNode* node, int level, const int& d, const int &v) {
if(level + 1 == d) {
node->left = new TreeNode(v, node->left, nullptr);
node->right = new TreeNode(v, nullptr, node->right);
return;
}

if(node->left != nullptr) {
rebalance(node->left, level + 1, d, v);
}

if(node->right != nullptr) {
rebalance(node->right, level + 1, d, v);
}

return;
}
public:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if(d == 1) {
root = new TreeNode(v, root, nullptr);
} else {
rebalance(root, 1, d, v);
}
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/09/PS/LeetCode/add-one-row-to-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.