Search This Blog

Tuesday, December 11, 2012

LeetCode:Populating Next Right Pointers in Each Node II

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
» Solve this problem

public class Solution {
    public void connect(TreeLinkNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(root==null) return;
        TreeLinkNode cur=root, 
                     top=root, 
                     first=null;
        cur.next = null;
        
        while(top!=null && cur!=null){
            cur=null;
            while(cur==null && top!=null){
                cur=(top.left==null)?top.right:top.left;
                if(cur==null) top=top.next;
            }
            if(cur!=null){
                first = cur;
                while(top!=null){
                    if(cur==top.left){
                        cur.next=top.right;
                        if(cur.next!=null) cur=cur.next;
                    }
                    top=top.next;
                    if(top!=null){
                        TreeLinkNode temp = null;
                        while(temp==null && top!=null){
                            temp=(top.left==null)?top.right:top.left;
                            if(temp==null)top=top.next;
                        }
                        cur.next=temp;
                        if(cur.next!=null) cur=cur.next;
                    }
                }   
                top=first;
            }
        }
        
    }
}

No comments: