给一个tree,定义height是根节点到叶子节点的距离中最短的一个,如何求出这个距离。
int height(Node *root)
{
if (root == NULL)
{
return 0;
}
if (root->left == NULL)
{
return 1 + height(root->right);
}
else if (root->right == NULL)
{
return 1 + height(root->left);
}
else
{
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return leftHeight < rightHeight? leftHeight+1 : rightHeight+1;
}
}