leetcode | Minimum Depth of Binary Tree
2015-07-03 15:12
351 查看
rMinimum Depth of Binary Tree : https://leetcode.com/problems/minimum-depth-of-binary-tree/
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,
最短路径(最小深度)则是选择左右子树中深度小的加 1。
需要注意的是,空节点不算叶节点,所以遇到空节点子树时,需要返回另一颗子树的深度加 1;在求树的深度时,选的是深度较大的一个,故不需考虑空节点子树。
如:[1 2 NULL] 返回 2
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,
最短路径(最小深度)则是选择左右子树中深度小的加 1。
需要注意的是,空节点不算叶节点,所以遇到空节点子树时,需要返回另一颗子树的深度加 1;在求树的深度时,选的是深度较大的一个,故不需考虑空节点子树。
如:[1 2 NULL] 返回 2
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //定义:NULL不是叶节点 class Solution { public: int minDepth(TreeNode* root) { if (root == NULL) return 0; if (root->left == NULL) // 左子树没有叶节点 return minDepth(root->right)+1; if (root->right == NULL) // 右子树没有叶节点 return minDepth(root->left)+1; return min(minDepth(root->left), minDepth(root->right)) + 1; } };
相关文章推荐
- 如何中断一个正在运行的线程
- socket常用函数解析(1)
- 黑马程序员---泛型,Collections,Arrays
- Swift基础语法学习总结
- Win7旗舰版打字的时候总是出现重复字符的解决方法
- oracle中往varchar2格式的字段中插入date时间格式的值会发生什么?
- JDK,JRE,JVM区别与联系
- Pinot架构介绍
- OCP认证考试心得
- jquery delayLoading.js插件的延迟加载效果和图片延迟加载
- DataReader使用
- C++ 11之 && 右值引用
- test
- 黑马程序员——java基础---面向对象
- 自制清理垃圾缓存软件
- 欢迎使用CSDN-markdown编辑器
- 8.16
- hadoop elcipse/intelliJ win7配置详解
- iOS 开发使用16进制色值设置颜色
- VBoxManage命令详解技术文章