-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulatingNextRightPointersInEachNodeII.java
More file actions
59 lines (49 loc) · 1.58 KB
/
PopulatingNextRightPointersInEachNodeII.java
File metadata and controls
59 lines (49 loc) · 1.58 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
58
59
package leetcode;
import utils.TreeNode;
import utils.Trees;
import java.util.Queue;
import java.util.concurrent.LinkedTransferQueue;
/**
* PopulatingNextRightPointersInEachNodeII
* https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
*
* @since 2020-09-28
*/
public class PopulatingNextRightPointersInEachNodeII {
public static void main(String[] args) {
Integer[] values = {1, 2, 3, 4, 5, null, 7};
TreeNode head = Trees.fromIntegers(values);
PopulatingNextRightPointersInEachNodeII sol = new PopulatingNextRightPointersInEachNodeII();
TreeNode res = sol.connect(head);
System.out.println(res.val);
}
public TreeNode connect(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> nodes = new LinkedTransferQueue<>();
Queue<Integer> levels = new LinkedTransferQueue<>();
nodes.add(root);
levels.add(0);
TreeNode last = null;
int lastLevel = -1;
while (!nodes.isEmpty()) {
TreeNode curr = nodes.poll();
int currLevel = levels.poll();
if (last != null && lastLevel == currLevel) {
last.next = curr;
}
if (curr.left != null) {
nodes.add(curr.left);
levels.add(currLevel + 1);
}
if (curr.right != null) {
nodes.add(curr.right);
levels.add(currLevel + 1);
}
last = curr;
lastLevel = currLevel;
}
return root;
}
}