LC.P623[在二叉树中增加一行]

方法一:BFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) return new TreeNode(val, root, null);
int currentDepth = 1;
Deque<TreeNode> queue = new ArrayDeque<>();
if (root != null) queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
TreeNode p = queue.poll();
if (depth - 1 == currentDepth) {
p.left = new TreeNode(val, p.left, null);
p.right = new TreeNode(val, null, p.right);
} else {
if (p.left != null) queue.offer(p.left);
if (p.right != null) queue.offer(p.right);
}
}
++currentDepth;
}
return root;
}
}
  • 时间复杂度;$O(n)$
  • 空间复杂度:$O(n)$

方法二:DFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

int depth, val;

public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) return new TreeNode(val, root, null);
this.depth = depth;
this.val = val;
dfs(root, 1);
return root;
}

private void dfs(TreeNode root, int cur) {
if (root == null) return;
if (cur == depth - 1) {
TreeNode a = new TreeNode(val), b = new TreeNode(val);
a.left = root.left;
b.right = root.right;
root.left = a;
root.right = b;
} else {
dfs(root.left, cur + 1);
dfs(root.right, cur + 1);
}
}
}
  • 时间复杂度;$O(n)$
  • 空间复杂度:$O(n)$