Monday, August 17, 2015

[Leetcode] Populating Next Right Pointers in Each Node I

For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->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) {
        
        
        /*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;
                }
                //if(curNum == 0)
                //{
                // newHead = cur.right;  
                //}
                curNum++;
            }
            if ( lastNum == 0 )
            {
                head = newHead;
                lastNum = curNum;
                curNum = 0;
                newHead = null;
                iterating = null;
            }
            else
            {
                head = head.next;
            }
        }
    }
}

No comments:

Post a Comment