【二叉树】111. Minimum Depth of Binary Tree
来源:互联网 发布:云计算学习视频 编辑:程序博客网 时间:2024/05/17 23:04
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行是错的:
class Solution {public: int minDepth(TreeNode* root) { return root==NULL?0:1+min(minDepth(root->left),minDepth(root->right)); }};这样写的错误在于,如果二叉树是斜的(也就是一个链表,没有左孩子或者右孩子),因为空的节点也参与了递归,那么min函数总是在这种地方取到
了0,这样的话返回的就只能是1了(也就是说最终只算了根节点。。。)
AC代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode* root) { if(!root) return 0;//递归用的边界,只有一个节点是1,下面的代码要+1,那么边界只能返回0 if(!root->left) return 1 + minDepth(root->right);//求右子树高度 if(!root->right) return 1 + minDepth(root->left);//求左子树高度 return 1+min(minDepth(root->left),minDepth(root->right));//根节点加上左子树/右子树中最小的高度的 }};
阅读全文
0 0
- 二叉树遍历111. Minimum Depth of Binary Tree
- 【二叉树】111. Minimum Depth of Binary Tree
- 【二叉树】计算二叉树深度【104. Maximum Depth of Binary Tree】【111. Minimum Depth of Binary Tree】
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- Minimum Depth of Binary Tree 二叉树的最小深度
- Minimum Depth of Binary Tree 二叉树最小深度
- Minimum Depth of Binary Tree 二叉树的最小深度
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- Minimum Depth of Binary Tree 二叉树的最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- leetCode 111.Minimum Depth of Binary Tree(二叉树最小深度) 解题思路和方法
- 111. Minimum Depth of Binary Tree 二叉树的最小深度
- LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)
- 111. Minimum Depth of Binary Tree 二叉树的最小深度
- Leetcode 111. Minimum Depth of Binary Tree 二叉树最小深度
- 111. Minimum Depth of Binary Tree (计算二叉树最小深度)
- [LeetCode]111. Minimum Depth of Binary Tree--二叉树的最小深度
- python_day1
- C++ 特化与重载(12)---《C++ Templates》
- C++学习之路 day1
- 2017.8.24 快速傅里叶 思考记录
- spark独立模式配置
- 【二叉树】111. Minimum Depth of Binary Tree
- JDBC常见面试题集锦
- 建造者模式在日志系统中的运用
- bzoj3238 [Ahoi2013]差异(SA+单调栈求所有区间最小值和)
- 人工智能很可能毁灭人类
- LintCode:M-Partition Array(快排变种)
- Android 屏幕适配攻略(六)设置通知样图标与启动图标适配
- 基于hadoop搜索引擎实践——生成倒排表文件(四)
- bzoj4973比特战争 kruskal