623 Add One Row to Tree

# 1. Question

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 valuevas the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
1
Input:
2
3
A binary tree as following:
4
4
5
/ \
6
2 6
7
/ \ /
8
3 1 5
9
10
11
v = 1
12
d = 2
13
Output:
14
15
4
16
/ \
17
1 1
18
/ \
19
2 6
20
/ \ /
21
3 1 5
Copied!
Example 2:
1
Input:
2
3
A binary tree as following:
4
4
5
/
6
2
7
/ \
8
3 1
9
10
11
v = 1
12
d = 3
13
Output:
14
15
4
16
/
17
2
18
/ \
19
1 1
20
/ \
21
3 1
Copied!
Note:
1. 1.
The given d is in range [1, maximum depth of the given tree + 1].
2. 2.
The given binary tree has at least one tree node.

# 2. Implementation

(1) BFS
1
class Solution {
2
public TreeNode addOneRow(TreeNode root, int v, int d) {
3
if (root == null) {
4
return root;
5
}
6
7
if (d == 1) {
8
TreeNode newRoot = new TreeNode(v);
9
newRoot.left = root;
10
return newRoot;
11
}
12
13
14
15
16
int curDepth = 1, size = 0;
17
boolean reach = false;
18
19
while (!queue.isEmpty()) {
20
size = queue.size();
21
22
for (int i = 0; i < size; i++) {
23
TreeNode curNode = queue.remove();
24
TreeNode leftSubTree = curNode.left;
25
TreeNode rightSubTree = curNode.right;
26
27
if (d - 1 == curDepth) {
28
curNode.left = new TreeNode(v);
29
curNode.right = new TreeNode(v);
30
curNode.left.left = leftSubTree;
31
curNode.right.right = rightSubTree;
32
reach = true;
33
}
34
else {
35
if (leftSubTree != null) {
36
37
}
38
if (rightSubTree != null) {
39
40
}
41
}
42
}
43
if (reach) {
44
break;
45
}
46
++curDepth;
47
}
48
return root;
49
}
50
}
Copied!
(2) DFS
1
class Solution {
2
public TreeNode addOneRow(TreeNode root, int v, int d) {
3
if (root == null) {
4
return root;
5
}
6
7
if (d == 1) {
8
TreeNode newRoot = new TreeNode(v);
9
newRoot.left = root;
10
return newRoot;
11
}
12
13
dfs(root, 1, v, d);
14
return root;
15
}
16
17
public void dfs(TreeNode node, int depth, int v, int target) {
18
if (node == null) {
19
return;
20
}
21
22
if (depth == target - 1) {
23
TreeNode leftSubTree = node.left;
24
TreeNode rightSubTree = node.right;
25
node.left = new TreeNode(v);
26
node.right = new TreeNode(v);
27
node.left.left = leftSubTree;
28
node.right.right = rightSubTree;
29
return;
30
}
31
32
dfs(node.left, depth + 1, v, target);
33
dfs(node.right, depth + 1, v, target);
34
}
35
}
Copied!

# 3. Time & Space Complexity

BFS: 时间复杂度O(n), 空间复杂度: O(w)
DFS: 时间复杂度O(n), 空间复杂度: O(d), d是输入里的d