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
分析:
这里我想到的是层序遍历,同时为了区分层,用两个队列交替的方式遍历。
我不知道这算不算constant space.
/**
* 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<TreeLinkNode>();
Queue<TreeLinkNode> q2 = new LinkedList<TreeLinkNode>();
q1.add(root);
while(q1.size()>0 || q2.size()>0){
while(q1.size()>0){
TreeLinkNode temp = q1.remove();
temp.next = q1.peek();
if(temp.left != null) q2.add(temp.left);
if(temp.right != null) q2.add(temp.right);
}
while(q2.size()>0){
TreeLinkNode temp = q2.remove();
temp.next = q2.peek();
if(temp.left != null) q1.add(temp.left);
if(temp.right != null) q1.add(temp.right);
}
}
}
}