Sunday, February 9, 2014

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
Solution: BFS transformation question.
 Traverse the tree level by level and maintain a previous pointer at each level.
/**
 * 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) {
        ArrayList queue = new ArrayList();
        if(root == null) return;
        queue.add(root);
        int currentLevelNum = 1;
        int nextLevelNum = 0;
        while(!queue.isEmpty()){
            boolean leftMost = true;
            TreeLinkNode prev = root; // random initialization.
            while(currentLevelNum > 0){
                currentLevelNum--;
                TreeLinkNode node = queue.remove(0);
                if(node.left != null){
                    queue.add(node.left);
                    nextLevelNum++;
                    if(leftMost){prev = node.left; leftMost = false;}
                    else{prev.next = node.left; prev = node.left;}
                }
                if(node.right != null){
                    queue.add(node.right);
                    nextLevelNum++;
                    if(leftMost){prev = node.right; leftMost = false;}
                    else{prev.next = node.right; prev = node.right;}
                }
            }
            currentLevelNum = nextLevelNum;
            nextLevelNum = 0;
        }
    }
}

No comments:

Post a Comment