117 Populating Next Right Pointers in Each Node II

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

using a queue

/**
 * 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> q = new LinkedList<>();

        q.add(root);

        while(!q.isEmpty()){
            int size = q.size();
            for(int i=0; i< size; i++){
                TreeLinkNode node = q.poll();
                node.next = (i == size-1)? null : q.peek();
                if(node.left != null) q.add(node.left);
                if(node.right != null) q.add(node.right);
            }
        }
    }
}
  • keep track of next level's first.
  • keep track of next level's last visited.
  • move current along its next chain.
/**
 * 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;

        //keep track of first node in next level,
        TreeLinkNode first = null;
        //and previous node in current level
        TreeLinkNode last = null;
        //and current visiting node
        TreeLinkNode current = root;
        root.next = null;

        while(current != null){
            //retrieve next first if is not set.
            if(first == null){
                if(current.left != null) first = current.left;
                else first = current.right;
            }

            if(current.left != null){
                if(last != null) last.next = current.left;
                // IT is not else, if last is not null, then step ahead last
                // to next which is current.left,
                //if last is null, then current.left become last;
                last = current.left;
            }
            if(current.right != null){
                if(last != null) last.next = current.right;
                last = current.right;
            }

            if(current.next != null){
                current = current.next;
            }else{
                current = first;
                first = last = null;
            }

        }
    }
}

results matching ""

    No results matching ""