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



和这个系列第一道题比较起来,少了一个完全二叉树的条件,那么就需要用迭代的方法去找next。

有一个注意事项是,要先做右子树,再作左子树,考虑以下情况:

1. l1和r1分别为root节点的两个子节点,如果说假设我们先做l1

2. 做到l1的右子节点的时候,需要到r1的子节点里面去找next,这时候如果r1的两个子节点都是空,那么需要继续到r1的next中去找,这时候因为我们先递归了l1,r1的next还没有被赋值,所以会出现丢失next的情况。


/**
 * 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) {
        if(root == null){
            return;
        }
        if(root.right!=null){
            root.right.next = findNext(root.next);
        }
        if(root.left!=null){
            root.left.next = root.right==null?findNext(root.next):root.right;
        }
        connect(root.right);
        connect(root.left);
    }
    public TreeLinkNode findNext(TreeLinkNode root){
        if(root==null){
            return null;
        }else{
            TreeLinkNode iter = root;
            TreeLinkNode result = null;
            while(iter!=null){
                if(iter.left!=null){
                    result = iter.left;
                    break;
                }
                if(iter.right!=null){
                    result = iter.right;
                    break;
                }
                iter = iter.next;
            }
            return result;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章