问题
I am very new to binary tree and recursion. My program is to find the height of the tree but I am a bit confused as to why my program doesn't work.
struct Node {
int value;
Node *left;
Node *right;
}
int heightOfTree(Node node){
if(node ==NULL)
{
return 0;
}
else
{
int lheight=heightOfTree(node->left);
int rheight = heightOfTree(node->right);
if(lheight>rheight)
{
return lheight;
}
else
{
return rheight;
}
}
}
I followed a pseudocode online so I implemented it myself because I don't want to just copy and paste. I tried to insert a lot of nodes but When I run my program I always get 0 height? Thank you
回答1:
return lheight + 1;
and
return rheight + 1;
You need to increment the height at each level.
来源:https://stackoverflow.com/questions/42463585/finding-depth-of-a-tree