二叉树的最大深度
采用递归的思想
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
int left_depth = maxDepth(root->left);
int right_depth = maxDepth(root->right);
return max(left_depth, right_depth) + 1;
}
};
二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
int left_depth = minDepth(root->left);
int right_depth = minDepth(root->right);
if (root->left == NULL && root->right != NULL)
return right_depth + 1;
else if (root->left != NULL && root->right == NULL)
return left_depth + 1;
else
return min(left_depth, right_depth) + 1;
}
};