Populating Next Right Pointers in Each Node II

来源:互联网 发布:python字符串转换列表 编辑:程序博客网 时间:2024/06/10 14:18
    public void connect(TreeLinkNode root) {        // Start typing your Java solution below        // DO NOT write main() function        while(root != null) {            TreeLinkNode tmp = root;            while(tmp != null) {                if(tmp.left != null || tmp.right != null) {                    TreeLinkNode uncle = tmp;                    while(uncle.next != null && uncle.next.left == null && uncle.next.right == null) {                        uncle = uncle.next;                    }                    TreeLinkNode next = null;                    if(uncle.next != null) next = (uncle.next.left == null) ? uncle.next.right : uncle.next.left;                    if(tmp.left != null) tmp.left.next = (tmp.right == null) ? next : tmp.right;                    if(tmp.right != null) tmp.right.next = next;                }                tmp = tmp.next;            }            while(root.next != null && root.left == null && root.right == null) {                root = root.next;            }            root = (root.left == null) ? root.right : root.left;        }    } 

原创粉丝点击