给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/
2 3
/
4 5
这个二叉树的最小深度为 2
分析:与最大深度有区别 有单孩子的情况考虑
/**
* 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
*/
int minDepth(TreeNode *root) {
// write your code here
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 1;
int Left=minDepth(root->left);
int Right=minDepth(root->right);
if(root->left==NULL)
{
return Right+1;
}
if(root->right==NULL)
{
return Left+1;
}
int depth=Left<Right?Left:Right;
return depth+1;
}
};