-
Notifications
You must be signed in to change notification settings - Fork 31
/
PopulateNextRight.java
75 lines (59 loc) · 1.44 KB
/
PopulateNextRight.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
package Trees;
/**
* Author - archit.s
* Date - 09/11/18
* Time - 4:13 PM
*/
public class PopulateNextRight {
public class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}
public TreeLinkNode getNext(TreeLinkNode p){
TreeLinkNode temp = p.next;
while(temp!=null){
if(temp.left!=null){
return temp.left;
}
else if(temp.right!=null){
return temp.right;
}
temp = temp.next;
}
return null;
}
public void connect(TreeLinkNode A) {
TreeLinkNode p = A;
if(p == null){
return;
}
p.next = null;
while(p!=null){
TreeLinkNode q = p;
while(q!=null){
if(q.left!=null){
if(q.right!=null){
q.left.next = q.right;
}
else{
q.left.next = getNext(q);
}
}
if(q.right!=null){
q.right.next = getNext(q);
}
q = q.next;
}
if(p.left!=null){
p = p.left;
}
else if(p.right!=null){
p = p.right;
}
else{
p = getNext(p);
}
}
}
}