-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
36 lines (36 loc) · 1.02 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
/**
* 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) {
if (root!=null) {
TreeLinkNode rootNext=root.next;
TreeLinkNode sonNext=null;
while (rootNext!=null&&sonNext==null) {
if (rootNext.left!=null) {
sonNext=rootNext.left;
}else {
sonNext=rootNext.right;
}
rootNext=rootNext.next;
}
if (root.left!=null) {
if (root.right!=null) {
root.left.next=root.right;
}else {
root.left.next=sonNext;
}
}
if (root.right!=null) {
root.right.next=sonNext;
}
connect(root.right);
connect(root.left);
}
}
}