【LeetCode】111. 二叉树的最小深度

算法现在就是大厂、外企的硬指标。开发、测开、测试,想往上总是绕不开的。

题目描述

难度:【简单】
标签:【二叉树】

给定一个二叉树,找出其最小深度。

说明:叶子节点是指没有子节点的节点。
题目地址:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

示例

示例 1:

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

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

题解

与之前的二叉树最大深度思路相似,递归的时候考虑这 3 种情况:

  • 左右孩子都为 null,说明到达了叶子节点,直接返回该节点本身的高度 1
  • 左右孩子有一个为 null,返回不为空的那个子树的高度,再加上 1
  • 左右孩子都不为null,返回比较后最小的,再加上 1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 左右孩子都为null,返回 1
        if (root.left == null && root.right == null) {
            return 1;
        }
        int leftHeight = minDepth(root.left);
        int rightHeight = minDepth(root.right);
        // 左右孩子有一个为null
        if (leftHeight == 0 || rightHeight == 0) {
            return leftHeight + rightHeight + 1;
        }
        // 左右孩子都不为null,返回比较最短的 + 1
        return Math.min(leftHeight, rightHeight) + 1;
    }
}
posted @ 2021-11-29 22:59  把苹果咬哭的测试笔记  阅读(32)  评论(0编辑  收藏  举报