-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path117.populating-next-right-pointers-in-each-node-ii.java
More file actions
46 lines (46 loc) · 1.32 KB
/
117.populating-next-right-pointers-in-each-node-ii.java
File metadata and controls
46 lines (46 loc) · 1.32 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
/**
* 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) return;
else root.next=null;
TreeLinkNode pre = root;
TreeLinkNode head = null;
TreeLinkNode now = null;
while(pre!=null){
while(pre!=null){
if (pre.left!=null){
head = pre.left;
now = head;
break;
}
if (pre.right!=null) {
head = pre.right;
now = head;
break;
}
pre=pre.next;
}
while(pre!=null){
if (pre.left!=null&&pre.left!=now){
now.next = pre.left;
now = now.next;
}
if (pre.right!=null&&pre.right!=now){
now.next = pre.right;
now = now.next;
}
pre=pre.next;
}
if (now!=null) now.next = null;
pre = head;
head = null;
}
}
}