-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulatingNextRightPointers.java
More file actions
103 lines (95 loc) · 2.8 KB
/
populatingNextRightPointers.java
File metadata and controls
103 lines (95 loc) · 2.8 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class Solution {
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return;
Queue<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
q.add(root);
int num=1;
while(!q.isEmpty()) {
int i=num;
num=0;
TreeLinkNode pre=null;
while(i-->0) {
TreeLinkNode n=q.remove();
if(pre==null) pre=n;
else {
pre.next=n;
pre=n;
}
if(n.left!=null) {
q.add(n.left);
num++;
}
if(n.right!=null) {
q.add(n.right);
num++;
}
}
}
}
}
public class Solution {
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
c(root);
}
public TreeLinkNode c(TreeLinkNode root) {
if(root==null||(root.left==null&&root.right==null))
return root;
TreeLinkNode l=c(root.left);
TreeLinkNode r=c(root.right);
l.next=r;
while(l.right!=null) {
l.right.next=r.left;
l=l.right;
r=r.left;
}
return root;
}
}
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root || (!root->left && !root->right))
return;
root->left->next = root->right;
if (root->next)
root->right->next = root->next->left;
connect(root->left);
connect(root->right);
}
public void connect(TreeLinkNode root) {
TreeLinkNode first = root;
while (first != null) {
TreeLinkNode cur = first;
// set up next pointers for the next level
while (cur != null) {
if (cur.left != null) cur.left.next = cur.right;
if (cur.right != null && cur.next != null) cur.right.next = cur.next.left;
cur = cur.next;
}
// move to next level
first = first.left;
}
}
// the link of level(i) is the queue of level(i+1)
void connect(TreeLinkNode * n) {
while (n) {
TreeLinkNode * next = NULL; // the first node of next level
TreeLinkNode * prev = NULL; // previous node on the same level
for (; n; n=n->next) {
if (!next) next = n->left?n->left:n->right;
if (n->left) {
if (prev) prev->next = n->left;
prev = n->left;
}
if (n->right) {
if (prev) prev->next = n->right;
prev = n->right;
}
}
n = next; // turn to next level
}
}