每日一道 LeetCode (27):二叉树的最小深度

每天 3 分钟,走上算法的逆袭之路。

前文合集

每日一道 LeetCode 前文合集

代码仓库

GitHub: https://github.com/meteor1993/LeetCode

Gitee: https://gitee.com/inwsy/LeetCode

题目:路径总和

题目来源:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2 。

解题思路

今天做题的时候才看到,我昨天竟然跳过了一道题,我自己都没发现。

这道题看了以后总感觉前面做过,果然我往前翻了翻,看到前面第 22 天做的题是求最大深度,这道题是求最小深度。

二叉树求最小深度,我第一个想法就是通过迭代来做,一层一层的做循环,每循环一层,就看下这一层有没有存在叶子节点(左右子树都是 null )的节点,如果有,就接着往下循环,如果没有,那就可以直接返回了。

解题方案一:迭代

解题流程上面已经讲得很清楚了,下面是代码实现:

public int minDepth(TreeNode root) {
    if (root == null) return 0;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);

    int depth = 0;

    while (!queue.isEmpty()) {
        int size = queue.size();
        while (size > 0) {
            TreeNode node = queue.poll();
            if (node.left == null && node.right == null) {
                return depth + 1;
            }
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
            size--;
        }
        ++depth;
    }
    return depth;
}

这段代码就不解释了吧,经常看的同学应该都很清楚了,使用队列循环是循环二叉树最基本的方案。

解题方案二:递归

上面这个迭代的方案实际上是对广度优先搜索的一种实现,而深度优先搜索的实现,则是由递归来进行实现的。

public int minDepth_1(TreeNode root) {
    if (root == null) {
        return 0;
    }

    if (root.left == null && root.right == null) {
        return 1;
    }

    int min_depth = Integer.MAX_VALUE;
    if (root.left != null) {
        min_depth = Math.min(minDepth_1(root.left), min_depth);
    }
    if (root.right != null) {
        min_depth = Math.min(minDepth_1(root.right), min_depth);
    }

    return min_depth + 1;
}

使用深度优先搜索,实际上我们是计算了每一个非叶子节点的左右子树的最小深度,然后我们把取得的最小深度返回就结束了。

posted @ 2020-08-26 08:52  极客挖掘机  阅读(213)  评论(0编辑  收藏  举报