问题描述
笔记
与求最大深度不同的是,求最小深度要考虑到左孩子或者右孩子为空的情况。如果左孩子或者右孩子为空,空的那一边不能用来计算深度,因此要求max(取非空那一边的深度),而不是求min。
代码
/**
* 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;
int ldepth = minDepth(root->left);
int rdepth = minDepth(root->right);
if (root->left == NULL || root->right == NULL)
{
return max(ldepth, rdepth) + 1;
}
else
{
return min(ldepth, rdepth) + 1;
}
}
};