117. Populating Next Right Point
2018-04-05 本文已影响10人
衣介书生
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
这道题目可以将两个队列结合起来进行层次遍历。
import java.util.*;
/**
* 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;
}
Queue<TreeLinkNode> q1 = new LinkedList<>();
Queue<TreeLinkNode> q2 = new LinkedList<>();
q1.offer(root);
while(!q1.isEmpty()) {
TreeLinkNode temp = q1.poll();
if(q1.isEmpty()) {
temp.next = null;
} else {
temp.next = q1.peek();
}
if(temp.left != null) {
q2.offer(temp.left);
}
if(temp.right != null) {
q2.offer(temp.right);
}
if(q1.isEmpty() && !q2.isEmpty()) {
while(!q2.isEmpty()) {
q1.offer(q2.poll());
}
}
}
}
}