*LeetCode-Populating Next Right Pointers in Each Node

这个题很巧妙

要一层一层的做 每一层记录一下第一个node 用来进入下一层 然后一个指针在这一层中向后 每次添加的是指针所在层的下一层的next

像那种right child 它的next指向parent.next.left


public class Solution {
    public void connect(TreeLinkNode root) {
        if ( root == null )
            return;
        TreeLinkNode pre = root;
        TreeLinkNode cur = root;
        while( pre.left != null ){
            cur = pre;
            while ( cur != null ){
                cur.left.next = cur.right;
                if ( cur.next != null )
                    cur.right.next = cur.next.left;
                cur = cur.next;
            }
            pre = pre.left;
        }
    }
}
recursice

public class Solution {
    public void connect(TreeLinkNode root) {
        if ( root == null )
            return;
        if ( root.left != null ){
            root.left.next = root.right;
            if ( root.next != null) 
                root.right.next = root.next.left;
        }
        connect ( root.left);
        connect ( root.right);
    }
}



你可能感兴趣的:(*LeetCode-Populating Next Right Pointers in Each Node)