[LeetCode]Populating Next Right Pointers in Each Node II

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        TreeLinkNode pre = root;
        TreeLinkNode next = find_next(pre);
        while (next != null) {
            TreeLinkNode tmp = next;
            while (pre != null) {
                if (tmp == pre.left) {
                    if (pre.right != null) {
                        tmp.next = pre.right;
                        tmp = tmp.next;
                        pre = pre.next;
                    } else {
                        pre = pre.next;
                    }
                } else {
                    if (pre.left != null) {
                        tmp.next = pre.left;
                        tmp = tmp.next;
                    } else if (pre.right != null && tmp != pre.right) {
                        tmp.next = pre.right;
                        pre = pre.next;
                        tmp = tmp.next;
                    } else {
                        pre = pre.next;
                    }
                }
            }
            pre = next;
            next = find_next(next);
        }
    }
    public TreeLinkNode find_next (TreeLinkNode pre) {
        if (pre.left != null) {
            return pre.left;
        } else if (pre.right != null) {
            return pre.right;
        } else if (pre.next != null) {
            return find_next(pre.next);
        } else {
            return null;
        }
    }
}

 

posted @ 2015-12-02 11:58  Weizheng_Love_Coding  阅读(145)  评论(0编辑  收藏  举报