【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS)

题目描述

  • 很烦…面试被这题干碎了,赶紧给查漏补缺一波!
    在这里插入图片描述
    在这里插入图片描述

思路 && 代码

  • 主要思路:先右,再左(因为左边依赖右边!)
  • getNext():当前节点,无法包办子节点的 next 了,这份责任交给当前节点的 next !当然,如果 next 不行,那么继续递归传递责任(有点像责任链模式)
  • 对了,不一定得层序 BFS,因为对于当前节点来说,只要右边已经维护了就行。
  • 其他见注释~已经拉满注释了~
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    // 总思路:在当前层已经完善 next 的情况下,用当前层信息,对下一层进行维护
    public Node connect(Node root) {
        // Case 1:空节点
        if(root == null) return root;
        // Case 2:左右双全:直接左指右
        if(root.left != null && root.right != null) {
            root.left.next = root.right;
        }
        // Case 3: 有左无右:靠你了,我的下一个节点!
        if(root.left != null && root.right == null) {
            root.left.next = getNext(root.next); // 传入 root 的 next,用以获取可行的 next
        }
        // Case 4: 有右
        if(root.right != null) {
            root.right.next = getNext(root.next); // 同 Case 3
        }
        // 先右再左:因为得先获得右边节点的 next
        connect(root.right);
        connect(root.left);
        return root;
    }

    // 获取第一个节点。
    Node getNext(Node root) {
        // Case 1:为空:直接返回 null
        if(root == null) return null; 
        // Case 2:有左:返左节点
        if(root.left != null) return root.left;
        // Case 3:有右:返右节点
        if(root.right != null) return root.right;
        // Case 4:左右都没有,但是有下一个节点:继续递归查找
        if(root.next != null) return getNext(root.next);
        // Case 5:摆烂,啥都没有:那就只能 null 了。
        return null;
    }
}
  • 无注释版,其实就 16 行解决!
class Solution {
    public Node connect(Node root) {
        if(root == null) return null;
        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);
        connect(root.left);
        return root;
    }

    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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值