二叉树的最小深度
来源:互联网 发布:厦门市公安局网络公章 编辑:程序博客网 时间:2024/04/30 15:48
题目描述:
给定一个二叉树,找出其最小深度。
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
解题思路:
和求解二叉树的最大深度类似,先判断根节点是否为空,若为空,返回0;再判断根节点的左子树和右子树是否为空,若同时为空,返回1;若左子树或者右子树其中之一为空,则求解不为空子树的最小深度,然后加1;若左子树和右子树都不为空,则比较左子树和右子树的最小深度,然后加1,得到二叉树的最小深度。
代码实现:
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int minDepth(TreeNode *root) {
// write your code here
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
if(root->left==NULL)
return minDepth(root->right)+1;
if(root->right==NULL)
return minDepth(root->left)+1;
int leftDepth=minDepth(root->left);
int rightDepth=minDepth(root->right);
return leftDepth<rightDepth?(leftDepth+1):(rightDepth+1);
}
感想:
求解最小深度,要从根节点多方面考虑,涉及到每一种情况的出现。
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 一种简单的单链表逆序、反转的方法
- 用优雅的方式重装Windows 10不可使用的应用程序
- Array对象
- hdu1754 I Hate It
- 自定义注解开发
- 二叉树的最小深度
- connect & send 在三次握手过程中的有趣问题
- leetcodeOJ 43. Multiply Strings
- ThreadLoacal引起的内存泄露
- 文章标题
- 安全测试简介
- Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:错误
- OpenThreads库的使用-Mutex
- 编译领域会议列表