Saturday, January 10, 2015

LeetCode 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
/**
 * 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) {
        // LevelOrder
        // Consider the end node of every level (x.next = null)
        // Pre-save previous node when traverse current node
        if (root == null)
            return;
            
        Queue<TreeLinkNode> queue = new LinkedList<>();
        TreeLinkNode pre = null; // Previous node
        int count = 0;
        int curMode = 1; // Number of nodes of current level
        int nxtMode = 0; // Number of nodes of next level
        
        queue.add(root);
        
        while (!queue.isEmpty())
        {
            TreeLinkNode x = queue.remove();
            
            if (pre != null)
                pre.next = x;
            
            count++;
            
            // Verify if current node is the last node of the level or not
            if (count % curMode == 0)
            {
                count = 0;
                pre = null;
            }
            else
                pre = x;
            
            if (x.left != null)
            {
                queue.add(x.left);
                nxtMode++; // Count the number of next level node
            }
                
            if (x.right != null)
            {
                queue.add(x.right);
                nxtMode++;
            }
            
            // When reached the end of the level, assign next mode to current mode.
            // Next mode then reset to 0.
            if (count == 0)
            {
                curMode = nxtMode;
                nxtMode = 0;
            }
        }
    }
}

No comments:

Post a Comment