刷刷刷 Day 16 | 111. 二叉树的最小深度

111. 二叉树的最小深度

LeetCode题目要求

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。

图

示例

输入:root = [3,9,20,null,null,15,7]
输出:2
解题思路

与求最大深度不同的是,不能直接找最大值,而是要注意,有可能根节点无 左或右 子节点。所以会出现计算错误的情况
所以应该根据节点判断,没有了叶子节点时,才计算深度

上代码,递归

class Solution {
    public int minDepth(TreeNode root) {

        if (root == null) {
            return 0;
        }

        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        if (root.left == null) {
            return rightDepth + 1;
        }

        if (root.right == null) {
            return leftDepth + 1;
        }

        return Math.min(leftDepth, rightDepth) + 1;
    }
}

附:学习资料链接

posted @ 2023-01-20 20:27  blacksonny  阅读(18)  评论(0)    收藏  举报