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
Subscribe to see which companies asked this question
public class Solution {
private Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
public void connect(TreeLinkNode root) {
if(root == null) return ;
q.offer(root);
while(!q.isEmpty()){
TreeLinkNode node = q.poll();
if(node.left !=null){
q.offer(node.left);
}
if(node.right !=null){
q.offer(node.right);
}
TreeLinkNode leftNode = node.left;
TreeLinkNode rightNode = node.right;
TreeLinkNode oneChild = null;
if(leftNode!=null && rightNode!=null){
leftNode.next = rightNode;
oneChild = rightNode;
}
else if(leftNode!=null){
oneChild = leftNode;
}
else if(rightNode!=null){
oneChild = rightNode;
}
TreeLinkNode tmp = node.next;
while( oneChild!=null && tmp!=null){
if(tmp.left!=null){
oneChild.next = tmp.left;
break;
}
else if(tmp.right!=null){
oneChild.next = tmp.right;
break;
}
tmp = tmp.next;
}
}
}
}