-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulatingNextRightPointersInEachNode.java
More file actions
57 lines (50 loc) · 1.67 KB
/
PopulatingNextRightPointersInEachNode.java
File metadata and controls
57 lines (50 loc) · 1.67 KB
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
51
52
53
54
55
56
57
package leetcode;
import utils.TreeNode;
import utils.Trees;
import java.util.Queue;
import java.util.concurrent.LinkedTransferQueue;
/**
* PopulatingNextRightPointersInEachNode
* https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
*
* @since 2020-10-15
*/
public class PopulatingNextRightPointersInEachNode {
public static void main(String[] args) {
TreeNode head = Trees.fromIntegers(new Integer[]{1, 2, 3, 4, 5, 6, 7});
PopulatingNextRightPointersInEachNode sol = new PopulatingNextRightPointersInEachNode();
TreeNode res = sol.connect(head);
System.out.println(res.val);
}
public TreeNode connect(TreeNode root) {
if (root == null) { // 小坑一下
return root;
}
Queue<TreeNode> visits = new LinkedTransferQueue<>();
Queue<Integer> levels = new LinkedTransferQueue<>();
visits.add(root);
levels.add(0);
while (!visits.isEmpty() && !levels.isEmpty()) {
TreeNode curr = visits.poll();
int currLevel = levels.poll();
if (visits.isEmpty() || levels.isEmpty()) {
curr.next = null;
} else {
if (levels.peek().equals(currLevel)) {
curr.next = visits.peek();
} else {
curr.next = null;
}
}
if (curr.left != null) {
visits.add(curr.left);
levels.add(currLevel + 1);
}
if (curr.right != null) {
visits.add(curr.right);
levels.add(currLevel + 1);
}
}
return root;
}
}