您的位置:首页 > 其它

二叉树最大深度和最小深度

2017-05-22 21:35 363 查看

二叉树的最大深度

int maxDepth(TreeNode *root) {
// write your code (here)
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);

return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}


二叉树的最小深度

int minDepth(TreeNode *root) {
// write your code here
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL)
return 1;

int leftDepth = minDepth(root->left);
if(leftDepth == 0)
leftDepth = INT_MAX;

int rightDepth = minDepth(root->right);
if(rightDepth == 0)
rightDepth = INT_MAX;

return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: