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;
        }
    }
}


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