117. Populating Next Right Pointers in Each Node II

解题思路:
和Populating Next Right Pointers in Each Node(https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)一样采用dfs,但是注意在dfs的时候需要多做一些next节点是否存在的判断。并且需要注意的是,DFS时要先遍历right son, 再遍历left son。
如下例:
2
1 3
0 7 9 1
1 1 0 8 8
若先搜索left son,再搜索right son,在遍历到值为7的节点,9->1的next连接还没有建立。

代码如下:

public class Solution {
    //most right son in the next generation
    public TreeLinkNode mostRightSon(TreeLinkNode root){
        if (root == null)
            return null;
        else
            return (root.right == null) ? root.left : root.right;
    }

    //most left son of root.next(or root.next.next...) in the next generation
    public TreeLinkNode mostLeftSon(TreeLinkNode root){
        TreeLinkNode node = root;
        while(node != null){
            if (node.left != null)
                return node.left;
            else if (node.right != null)
                return node.right;
            else
                node = node.next;
        }
        return null;
    }

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

        TreeLinkNode mostRightSon = mostRightSon(root);
        if (mostRightSon != null){
            mostRightSon.next = mostLeftSon(root.next);
        }

        //root.right must be processed before left, because this is a depth first search so that the next of your right cousin may not have been processed.
        connect(root.right);
        connect(root.left);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值