117. 填充每个节点的下一个右侧节点指针 II

 

 

class Solution {
    public Node connect(Node root) {
        if(root==null) return root;
        if(root.left!=null && root.right!=null){
            root.left.next=root.right;
        }
        if(root.left!=null && root.right==null){
            root.left.next=getNext(root.next);
        }
        if(root.right!=null)
            root.right.next=getNext(root.next);
        connect(root.right); //注意先递归右子树,防止找next的时候,连不起来的情况
        connect(root.left);
        return root;
    }

    public Node getNext(Node root){
        if(root==null) return null;
        if(root.left!=null) return root.left;
        if(root.right!=null) return root.right;
        if(root.next!=null) return getNext(root.next);
        return null;
    }
}

 

posted @ 2020-07-14 10:43  Sexyomaru  阅读(104)  评论(0编辑  收藏  举报