/
Solution.java
executable file
·76 lines (62 loc) · 1.9 KB
/
Solution.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode dummy = new TreeLinkNode(0);
while(root != null){
TreeLinkNode child = dummy;
dummy.next = null;
while(root != null){
if(root.left != null){
child.next = root.left;
child = child.next;
}
if(root.right != null){
child.next = root.right;
child = child.next;
}
root = root.next;
}
root = dummy.next;
}
}
}
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
static final TreeLinkNode ORPHAN = new TreeLinkNode(0);
TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){
if(parent == null) return null;
if(parent.left != null && parent.left != me){
return parent.left;
}
if(parent.right != null){
return parent.right;
}
return sib(ORPHAN, parent.next);
}
public void connect(TreeLinkNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null) return;
if(root.left != null){
root.left.next = sib(root.left, root);
}
if(root.right != null){
root.right.next = sib(ORPHAN, root.next);
}
connect(root.right);
connect(root.left);
}
}