码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Populating Next Right Pointers in Each Node II

时间:2015-12-02 14:14:52      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode]Populating Next Right Pointers in Each Node II

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5012558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!