-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSolution623.java
50 lines (42 loc) · 1.34 KB
/
Solution623.java
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
48
49
50
package leetcode.tree.levelorder;
import leetcode.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class Solution623 {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) {
TreeNode node = new TreeNode(val);
node.left = root;
return node;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int curDepth = 2;
while (!queue.isEmpty()) {
if (curDepth == depth) {
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode left = new TreeNode(val);
left.left = node.left;
node.left = left;
TreeNode right = new TreeNode(val);
right.right = node.right;
node.right = right;
}
break;
}
curDepth++;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return root;
}
}