Populating Next Right Pointers in Each Node

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

Discuss



对于第一问,满树来说。

public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode start=root;
        while(start!=null){
            TreeLinkNode p=start;
            start=p.left;
            if(start==null) break;
            TreeLinkNode pre=null;
            while(p!=null){
                if(pre!=null)
                    pre.next=p.left;
                p.left.next=p.right;
                pre=p.right;
                p=p.next;
            }
        }
    }
}

对于第二问,任意的二叉树来说

public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode start=root;
        while(start!=null){
            TreeLinkNode p=start;
            start=null;
            while(p!=null){
                if(p.left!=null){
                    start=p.left;break;
                }
                if(p.right!=null){
                    start=p.right;break;
                }
                p=p.next;
            }
            TreeLinkNode pre=null;
            while(p!=null){
                if(p.left!=null){
                    if(pre!=null)
                        pre.next=p.left;
                    pre=p.left;
                }
                if(p.right!=null){
                    if(pre!=null)
                        pre.next=p.right;
                    pre=p.right;
                }
                p=p.next;
            }
        }
    }
}



你可能感兴趣的:(Populating Next Right Pointers in Each Node)