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?

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
 1 public class Solution {
 2     public void connect(TreeLinkNode root) {
 3         TreeLinkNode left = root;
 4         while(left!=null){
 5             TreeLinkNode across = left;
 6             TreeLinkNode leftMost = null;
 7             while(across!=null){
 8                 if(across.left!=null){
 9                     if(leftMost==null)
10                         leftMost = across.left;
11                     across.left.next = findNextRight(across,true);
12                 }
13                 if(across.right!=null){
14                     if(leftMost==null)
15                         leftMost = across.right;
16                     across.right.next = findNextRight(across,false);
17                 }
18                 across = across.next;
19             }
20             left = leftMost;
21         }
22     }
23     public TreeLinkNode findNextRight(TreeLinkNode root,boolean isLeft){
24         if(isLeft){
25             if(root.right!=null) return root.right;
26         }
27         root = root.next;
28         while(root!=null){
29             if(root.left!=null)
30                 return root.left;
31             if(root.right!=null)
32                 return root.right;
33             root = root.next;
34         }
35         return null;
36     
37     }
38 }
View Code

 

 
posted @ 2014-02-17 02:07  krunning  阅读(205)  评论(0编辑  收藏  举报