forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulatingNextRightPointersInEachNode.java
More file actions
43 lines (43 loc) · 1.36 KB
/
PopulatingNextRightPointersInEachNode.java
File metadata and controls
43 lines (43 loc) · 1.36 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
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
//level order use extra space
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
LinkedList<TreeLinkNode> list = new LinkedList<TreeLinkNode>();
list.offer(root);
int count = 1;
while(list.peek() != null){
for(int i = 0; i < count; ++i){
TreeLinkNode node = list.pop();
if(i == count - 1)
node.next = null;
else
node.next = list.peek();
list.offer(node.left);
list.offer(node.right);
}
count *= 2;
}
}
//no extra space
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root != null){
if(root.left != null)
root.left.next = root.right;
if(root.right != null)
root.right.next = root.next != null?root.next.left:null;
connect(root.left);
connect(root.right);
}
}
}