zoukankan      html  css  js  c++  java
  • 每日一道 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;
    }
    

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

    扫描二维码关注「极客挖掘机」公众号!
    作者:极客挖掘机
    定期发表作者的思考:技术、产品、运营、自我提升等。

    本文版权归作者极客挖掘机和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    如果您觉得作者的文章对您有帮助,就来作者个人小站逛逛吧:极客挖掘机
  • 相关阅读:
    JavaScript 消息框
    DOM事件
    修改输入框placeholder文字默认颜色-webkit-input-placeholder
    css—文字渐变色
    css—各浏览器下的背景色渐变
    $.ajax()方法详解
    使用meta实现页面的定时刷新或跳转
    python的连接mysql的安装
    django安装
    速查
  • 原文地址:https://www.cnblogs.com/babycomeon/p/13563107.html
Copyright © 2011-2022 走看看