Lintcode---二叉树的最小深度
2017-06-28 10:55
141 查看
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。
二叉树的最小深度为根节点到最近叶子节点的距离。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ /* 思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。 反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。 另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。 */ int minDepth(TreeNode *root) { // write your code here if(root==NULL){ return 0; } if(root->right==NULL){ return minDepth(root->left)+1; } if(root->left==NULL){ return minDepth(root->right)+1; } return min(minDepth(root->left),minDepth(root->right))+1; } };
相关文章推荐
- lintcode : 二叉树的最小深度
- lintcode-二叉树的最小深度-155
- lintcode--155. 二叉树的最小深度
- LintCode:二叉树的最小深度
- lintcode——二叉树的最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- lintcode&九章算法——No.97 二叉树的最大深度 ? 待解决
- lintcode——二叉树的最大深度
- LintCode-二叉树的最大深度
- Lintcode---二叉树的最大深度
- lintcode 二叉树的最大深度
- Lintcode-递归-97 二叉树的最大深度
- lintcode :二叉树的最大深度
- lintcode maximum-depth-of-binary-tree 二叉树的最大深度
- LintCode:二叉树的最大深度
- lintcode(480)——二叉树的所有路径
- 题目:二叉树的最小深度
- [lintcode]二叉树最大深度和最小深度
- [lintcode the-smallest-difference]最小差(python)
- LintCode 二叉树的层次遍历