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

849 阅读1分钟

题目描述

在这里插入图片描述

题解

递归遍历,记录深度,然后贪心地去更新结果(取min())。

考虑到这里还不够,需要加一层叶节点的判断,必须当前节点是叶子结点才能够做res的更新。否则可能会碰到这种情况:根结点左边没有子树,根结点右边有子树,结果递归下去发现深度是1(只考虑了左边没子树的情况,没有考虑到此时并不是叶子结点,而是根结点)

执行用时:6 ms, 在所有 Java 提交中击败了57.73%的用户

内存消耗:58.9 MB, 在所有 Java 提交中击败了22.96%的用户

通过测试用例:52 / 52

/**
 * 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 {
    private int res = Integer.MAX_VALUE;
    
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        depth(root, 0);
        return res;
    }
    
    public void depth(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res = Math.min(res, depth + 1);
        }
        // System.out.println(root.val + " " + depth);
        depth(root.left, depth + 1);
        depth(root.right, depth + 1);
    }
}