2015年6月11日星期四

Populating Next Right Pointers in Each Node II leetcode

FFor 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
a这道题的binary tree不一定是完整的 所以root.right.next指向是不定的 思路就是先找到root.right 右边第一个可行node存储
注意这道题应该先遍历右边然后再左边
时间O(n) 空间O(1)
public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        TreeLinkNode tem = root.next;
        while (tem != null) {
            if (tem.left != null) {
                tem = tem.left;
                break;
            } else if (tem.right != null) {
                tem = tem.right;
                break;
            } else {
                tem = tem.next;
            }
        }
        if (root.right != null) {
            root.right.next = tem;
        }
        if (root.left != null) {
            if (root.right != null) {
                root.left.next = root.right;
            } else {
                root.left.next = tem;
            }
        }
        connect(root.right);
        connect(root.left);
    }
}

没有评论:

发表评论