当前位置: 首页 > article >正文

闯关leetcode——111. Minimum Depth of Binary Tree

大纲

  • 题目
    • 地址
    • 内容
  • 解题
    • 代码地址

题目

地址

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

内容

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example 1:
在这里插入图片描述

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

解题

这题要求出一棵树中,从根节点到叶子节点的最短路径长度。这种题目基本都是要进行遍历,但是遍历时有优化空间。比如当某个节点的深度已经超过当前遍历过的最短路径,那么这个节点的子树就不用遍历了。

class Solution {
public:
    int minDepth(TreeNode* root) {
        int currentMinDepth = INT_MAX;
        return minDepthDfs(root, 0, currentMinDepth);
    }

private:
    int minDepthDfs(TreeNode* root, int depth, int currentMinDepth) {
        if (root == nullptr) return depth;

        depth++;

        if (depth >= currentMinDepth) return depth;

        if (root->left == nullptr && root->right == nullptr) return depth;

        if (root->left != nullptr) {
            currentMinDepth = min(currentMinDepth, minDepthDfs(root->left, depth, currentMinDepth));
        }

        if (root->right != nullptr) {
            currentMinDepth = min(currentMinDepth, minDepthDfs(root->right, depth, currentMinDepth));
        }

        return currentMinDepth;
    }
};

如果我们不考虑这种优化,要走到所有的叶子节点,则可以使用如下的代码。这段代码虽然简洁,但是还是存在优化空间。

    int minDepthDfs(TreeNode* root) {
        if (root == nullptr) return INT_MAX;
        if (root->left == nullptr && root->right == nullptr) return 1;
        return 1 + min(minDepthDfs(root->left), minDepthDfs(root->right));
    }

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/111-Minimum-Depth%20of-Binary-Tree


http://www.kler.cn/news/362014.html

相关文章:

  • SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
  • 【Unity】Unity中调用手机的震动功能 包括安卓和IOS
  • 马拉车算法(C/C++)
  • ECHO-GL:盈利电话驱动的异质图学习股票 走势预测
  • 中​国​移​动​黑​龙​江​​正​浩​创​新​一​面
  • Python基础Day14
  • juzigei/基于Java语言的充电桩系统(充电桩小程序+充电桩管理平台)
  • c++初阶数据结构速成
  • 监控易监测对象及指标之:东方通中间件JMX监控
  • Collection 单列集合 List Set
  • 【含文档】基于ssm+jsp的汉服商城网站 (含源码+数据库+lw)
  • 基于图像加密解密算法
  • 专题十三_记忆化搜索_算法专题详细总结
  • 目标检测系统中需要【重新训练模型】说明
  • LeetCode122:买卖股票的最佳时机II
  • 力扣力扣力:206. 反转链表
  • java项目结构说明
  • scrapy的xpath在控制台可以匹配,但是到了代码无法匹配(无法匹配tbody标签)
  • 金融行业:办公安全防护专属攻略
  • 三、MyBatis实践(2):MyBatis基本使用
  • 中国云厂出海:如何绕过暗礁,找到宝藏?
  • 10·24程序员节的思考:代码编织梦想,技术点亮未来
  • HBuilder X 中Vue.js基础使用1(三)
  • Vue学习一
  • 萤石云服务支持云端视频AI自动剪辑生成
  • 前端-基础CSS总结常用