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
/** * 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> queue1 = new LinkedList<TreeLinkNode>(); Queue<TreeLinkNode> queue2 = new LinkedList<TreeLinkNode>(); queue1.offer(root); TreeLinkNode pre = root; TreeLinkNode p = null; while (!queue1.isEmpty()||!queue2.isEmpty()){ while (!queue1.isEmpty()) { p = queue1.poll(); pre.next = p; pre = p; if (p.left!=null) { queue2.offer(p.left); } if (p.right!=null) { queue2.offer(p.right); } } if (p!=null){ p.next = null; } if (!queue2.isEmpty()) { pre = queue2.peek(); } while (!queue2.isEmpty()) { p = queue2.poll(); pre.next = p; pre = p; if (p.left!=null) { queue1.offer(p.left); } if (p.right!=null) { queue1.offer(p.right); } } if (p!=null){ p.next = null; } if (!queue1.isEmpty()) { pre = queue1.peek(); } } } }