LeetCode 111. Minimum Depth of Binary Tree
2016-06-17 16:31
393 查看
问题描述:
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.
此题联想到104. Maximum Depth of Binary Tree,如果将14题的代码单纯的改为如下:
int minDepth(TreeNode* root)
{
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return (left > right)?(left+1):(right+1);
}
则会出现单支的情况会有错误,即根节点只有左子树或者右子树,这时会返回1,而实际情况是要返回根节点到叶节点的最短距离,因此需要做一个左右子树是否为空的判断,如正确解法中的解答。
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.
int minDepth(TreeNode* root) { if(root == NULL) return 0; if(root->left == NULL) return minDepth(root->right)+1; else if(root->right == NULL) return minDepth(root->left)+1; else return min(minDepth(root->left),minDepth(root->right))+1; }
此题联想到104. Maximum Depth of Binary Tree,如果将14题的代码单纯的改为如下:
int minDepth(TreeNode* root)
{
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return (left > right)?(left+1):(right+1);
}
则会出现单支的情况会有错误,即根节点只有左子树或者右子树,这时会返回1,而实际情况是要返回根节点到叶节点的最短距离,因此需要做一个左右子树是否为空的判断,如正确解法中的解答。
相关文章推荐
- JS模拟bootstrap下拉菜单效果实例
- POJ 3461 kmp计算子串(可重叠)的个数
- 推荐系统中隐语义模型
- redis常见的命令
- # Android中的任务和返回栈总结
- oracle数据库的逻辑构成(表空间,schema,user,段,区,块)
- 上期ctp期货API android 客户端
- 亲子之间,在于看懂,无关耐心zz
- Codeforces Round #357 (Div. 2) 优先队列+模拟
- LSTM网络(Long Short-Term Memory )
- mysql bin log日志
- linux asm汇编例子
- Tbs_P1:创建、更改和删除表空间
- 设计模式-7种结构型【占坑中】
- js判断是Android系统还是ios系统
- 第十六周阅读程序4(1)
- JAVA I/O知识梳理
- keil5编译时出现 MDK-Pro middleware is not allowed with this license
- JQuery 事件
- 再vs2012下VTK程序不能调试解决办法