题目

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.

分析

求二叉树的最小深度:根节点到最近叶子节点的路径长度。

同样采用递归的思想:

  1. 当根节点为空,返回0;
  2. 当根节点为唯一的二叉树节点时,返回1;
  3. 否则,求解并返回 最小(非空,保证最终到达叶节点)左右子树深度 + 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;
} }
};

GitHub测试程序源码

最新文章

  1. FixFFmpeg 修改官方编译的ffmpeg能在 XP 上运行的工具
  2. [字符哈希] POJ 3094 Quicksum
  3. C# unity3d 贪吃蛇 游戏 源码 及其感想
  4. 返回标量CLR自定义函数
  5. Myeclipse8.5 反编译插件 jad 安装
  6. 使用PHP导入和导出CSV文件
  7. apache和php扩展问题
  8. php 操作mongodb
  9. linux 查看文件命令总结
  10. easyui 常用代码
  11. Keil使用中的若干问题
  12. 查看php的配置文件Php.ini的位置
  13. [洛谷P1196][NOI2002]银河英雄传说 - 带偏移量的并查集(1)
  14. 安卓TV开发(十) 智能电视开发之在线视频直播
  15. Mongo 用户管理
  16. 多功能网页刷新工具,刷pv工具
  17. 持续集成之④:GitLab触发jenkins构建项目
  18. day4-python基础-运算符
  19. POJ-3295 Tautology (构造)
  20. 高可用(HA)架构

热门文章

  1. [WOJ3010] 骰子
  2. Windows下打开某些软件时显示显卡驱动不是最新的问题
  3. HashMap源码及原理
  4. Storm编程入门API系列之Storm的Topology多个tasks数目控制实现
  5. vue axios post不能本地json
  6. LN : Eden Polymorphic And OOP Design Pattern Abstract Factory
  7. dialog样式的activity设置activity的title为隐藏属性
  8. ios自定义日期、时间、城市选择器
  9. java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/xxx/lib/arm/liblame.so: has text relocations
  10. C# 语言 类