1.描述:
给定一个二叉树,找出其最小深度。
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
3.代码:
int minDepth(TreeNode *root) {
if(root==NULL) return 0;
if(root->right==NULL&&root->left==NULL) return 1;
if(root->right==NULL&&root->left!=NULL)
{
return minDepth(root->left)+1;
}
if(root->right!=NULL&&root->left==NULL)
{
return minDepth(root->right)+1;
}
return min(minDepth(root->left)+1,minDepth(root->right)+1);
}
4.感想:
通过这道题,对递归的理解又深了一步,尤其是对其返回值的理解,调用是层层调用,返回也是层层返回。