您的位置:首页 > 其它

LeetCode 111. Minimum Depth of Binary Tree

2016-06-17 16:31 393 查看
问题描述:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
int minDepth(TreeNode* root)
{
if(root == NULL)
return 0;
if(root->left == NULL)
return minDepth(root->right)+1;
else if(root->right == NULL)
return minDepth(root->left)+1;
else return min(minDepth(root->left),minDepth(root->right))+1;
}

此题联想到104. Maximum Depth of Binary Tree,如果将14题的代码单纯的改为如下:

int minDepth(TreeNode* root)
{
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return (left > right)?(left+1):(right+1);
}

则会出现单支的情况会有错误,即根节点只有左子树或者右子树,这时会返回1,而实际情况是要返回根节点到叶节点的最短距离,因此需要做一个左右子树是否为空的判断,如正确解法中的解答。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: