/
Solution.java
executable file
·53 lines (46 loc) · 1.33 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
/**
* 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 helper(TreeLinkNode root){
while(root != null) {
if(root.left == null) return;
root.left.next = root.right;
if (root.next != null) root.right.next = root.next.left;
else root.right.next = null;
root = root.next;
}
}
public void connect(TreeLinkNode root) {
while(root != null){
TreeLinkNode tmp= root;
helper(root);
root = tmp.left;
}
}
}
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null || root.left == null || root.right == null) return;
root.left.next = root.right;
if(root.next != null){
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}
}