LeetCode(111) Minimum Depth of Binary Tree
2024-08-28 23:28:29
题目
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.
分析
求二叉树的最小深度:根节点到最近叶子节点的路径长度。
同样采用递归的思想:
- 当根节点为空,返回0;
- 当根节点为唯一的二叉树节点时,返回1;
- 否则,求解并返回 最小(非空,保证最终到达叶节点)左右子树深度 + 1;
AC代码
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
//独立的根节点
else if (!root->left && !root->right)
return 1;
else{
int left_depth, right_depth;
if (root->left)
left_depth = minDepth(root->left);
else
left_depth = INT_MAX;
if (root->right)
right_depth = minDepth(root->right);
else
right_depth = INT_MAX;
return min(left_depth, right_depth) + 1;
}
}
};
最新文章
- FixFFmpeg 修改官方编译的ffmpeg能在 XP 上运行的工具
- [字符哈希] POJ 3094 Quicksum
- C# unity3d 贪吃蛇 游戏 源码 及其感想
- 返回标量CLR自定义函数
- Myeclipse8.5 反编译插件 jad 安装
- 使用PHP导入和导出CSV文件
- apache和php扩展问题
- php 操作mongodb
- linux 查看文件命令总结
- easyui 常用代码
- Keil使用中的若干问题
- 查看php的配置文件Php.ini的位置
- [洛谷P1196][NOI2002]银河英雄传说 - 带偏移量的并查集(1)
- 安卓TV开发(十) 智能电视开发之在线视频直播
- Mongo 用户管理
- 多功能网页刷新工具,刷pv工具
- 持续集成之④:GitLab触发jenkins构建项目
- day4-python基础-运算符
- POJ-3295 Tautology (构造)
- 高可用(HA)架构
热门文章
- [WOJ3010] 骰子
- Windows下打开某些软件时显示显卡驱动不是最新的问题
- HashMap源码及原理
- Storm编程入门API系列之Storm的Topology多个tasks数目控制实现
- vue axios post不能本地json
- LN : Eden Polymorphic And OOP Design Pattern Abstract Factory
- dialog样式的activity设置activity的title为隐藏属性
- ios自定义日期、时间、城市选择器
- java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/xxx/lib/arm/liblame.so: has text relocations
- C# 语言 类