forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext_right_pointer2.java
More file actions
48 lines (44 loc) · 1.15 KB
/
Next_right_pointer2.java
File metadata and controls
48 lines (44 loc) · 1.15 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
public class NextRightPointerII {
public static void main(String[] args) throws Exception {
TreeLinkNode root = new TreeLinkNode(1);
root.left = new TreeLinkNode(2);
root.right = new TreeLinkNode(3);
root.right.right = new TreeLinkNode(4);
root.right.right.left = new TreeLinkNode(5);
root.right.right.right = new TreeLinkNode(6);
new NextRightPointerII().connect(root);
}
public void connect(TreeLinkNode root) {
TreeLinkNode prev = new TreeLinkNode(0);
TreeLinkNode first = null;
while (root != null) {
if (root.left != null) {
prev.next = root.left;
prev = root.left;
if (first == null) {
first = root.left;
}
}
if (root.right != null) {
prev.next = root.right;
prev = root.right;
if (first == null) {
first = root.right;
}
}
root = root.next;
if (root == null) {
root = first;
first = null;
prev = new TreeLinkNode(0);
}
}
}
public static class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) {
val = x;
}
}
}