Monday, August 17, 2015

[Leetcode] Populating Next Right Pointers in Each Node II

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; }
 * }
 */
/*
Binary Tree Level Order Traversal Extension

*** only use constant extra space
so precious BFS with queue not working here

M1: BFS
Time:O(n) Space:O(1)


Runtime Error Message:
Line 54: java.lang.NullPointerException
Last executed input:
{7,-10,2,-4,3,-8,#,#,#,#,-1,11}
      7
  -10      2
-4  3   -8  #
## #-1  11
 */
public class Solution {
    public void connect(TreeLinkNode root) {

        /*BFS*/
        if (root == null)
        {
            return;
        }
        TreeLinkNode head = root; // use TreeLinkNode next feature as a queue
        TreeLinkNode newHead = null;
        TreeLinkNode iterating = null;
        int lastNum = 1;
        int curNum = 0;
        while ( head != null )
        {
            TreeLinkNode cur = head;
            lastNum--;
            if (cur.left != null)
            {
                if (curNum == 0)
                {
                    newHead = cur.left;
                    iterating = newHead;
                }
                else
                {
                    iterating.next = cur.left;
                    iterating = iterating.next;
                }
                curNum++;
            }
            if ( cur.right != null )
            {
                if ( curNum != 0 )
                {
                    iterating.next = cur.right;
                    iterating = iterating.next;
                }
                // major difference from Populating Next Right Pointers in Each Node I
                if(curNum == 0)
                {
                  newHead = cur.right; 
                  iterating = newHead;
                }
                curNum++;
            }

            if ( lastNum == 0 )
            {

                head = newHead;
                lastNum = curNum;
                curNum = 0;
                newHead = null;
                iterating = null;
            }
            else
            {
                head = head.next;
            }
        }
    }
}

No comments:

Post a Comment