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

题目链接

法一
    /**
     * 得到root的最左边孩子,若没有孩子,则递归的去找root.next的最左边孩子
     *
     * @param root
     * @return
     */
    private 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) { // 没有左右孩子,则返回root.next的最左边孩子
            return getNext(root.next);
        }
        return null;
    }

    /**
     * 遍历顺序:根 右 左
     * 如果先递归左子树,会出现左边无法与右边相连的case
     *
     * @param root
     * @return
     */
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        if (root.left != null && root.right != null) { // root有左右孩子
            root.left.next = root.right;  // root的左孩子连接到root的右孩子
        }
        if (root.left != null && root.right == null) { // root有左孩子,没有右孩子
            root.left.next = getNext(root.next); // root的左孩子连接到root.next的最左边孩子
        }
        if (root.right != null) { // root有右孩子,没有左孩子
            root.right.next = getNext(root.next); // root的右孩子连接到root.next的最左边孩子
        }
        connect(root.right); // 先遍历右子树
        connect(root.left);  // 再遍历左子树
        return root;
    }
本地测试
        /**
         * 117. 填充每个节点的下一个右侧节点指针 II
         */
        lay.showTitle(117);
        Solution117 sol117 = new Solution117();
        List<Integer> arr117 = Arrays.asList(1, 2, 3, 4, 5, null, 7);
        Node root117 = nextTreeOpt.createNextTreeByLayerOrder(arr117);
        nextTreeOpt.levelTraversal(root117);
        sol117.connect(root117);
        nextTreeOpt.levelTraversalByNext(root117);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值