forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulatingnextrightpointers.java
More file actions
executable file
·33 lines (33 loc) · 1.01 KB
/
populatingnextrightpointers.java
File metadata and controls
executable file
·33 lines (33 loc) · 1.01 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
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return;
Queue<TreeLinkNode> now = new LinkedList<TreeLinkNode>();
Queue<TreeLinkNode> next = new LinkedList<TreeLinkNode>();
now.offer(root);
while(!now.isEmpty() ){
TreeLinkNode tmp = new TreeLinkNode(0);
while(!now.isEmpty()){
TreeLinkNode t = now.poll();
tmp.next = t;
tmp = tmp.next;
if(tmp.left!=null && tmp.right!=null){
next.offer(tmp.left);
next.offer(tmp.right);
}
}
Queue<TreeLinkNode> t = now;
now = next;
next = t;
}
}
}