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

闯关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.mrgr.cn/news/52310.html

相关文章:

  • 【python爬虫实战】爬取全年天气数据并做数据可视化分析!附源码
  • 【MySQL】表的修改操作,插入查询结果
  • python爬虫实战案例——从移动端接口抓取微博评论,采用cookie登陆,数据存入excel表格,超详细(15)
  • 精英高匿ip的自述
  • PyQt5高级界面控件一
  • Java中使用protobuf
  • 江大白 | 目标检测YOLOv1-YOLO11,算法进化全记录(建议收藏!)
  • 双十一来袭,哪款宠物空气净化器值得入手?好用的宠物空净推荐
  • Redis-1
  • 每日OJ题_牛客_连续子数组最大和_线性dp_C++_Java
  • oracle 19c 配置开机自启动
  • 系统思考—战略共识
  • 10.17作业
  • 多态底层原理【附原理模型图】
  • 学习之上下文管理器
  • 提供综合康复服务的武汉自闭症全托管学校
  • 记一次有趣的发现-绕过堡垒机访问限制
  • 如何排查CPU占用率过高的问题
  • Redis过期Key的逐出策略
  • 潜水定位通信系统的功能和使用方法_鼎跃安全