int findHeight(struct BstNode* root)
{
if(root==NULL)
return -1;
return max(findHeight(root->left),findHeight(root->right))+1;
}
该函数始终返回1作为高度。 这是代码链接。 https://github.com/ashwinidotx/OpenIssues/blob/master/Height%20Of%20Binary%20Tree.c
代码很麻烦。当你到达叶子节点之外时,你将返回错误的-1
。这是在计算树高时进行减法。你应该在这里返回0
,因为你到了最后,那里没有节点。
这是更正的方法:
int findHeight(struct BstNode* root)
{
if(root == NULL)
return 0;
return 1 + max(findHeight(root->left), findHeight(root->right));
}