I was doing some exercise on
https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1
Here is the input format that has been used.
I see that their implementation has number of nodes traversed and not number of edges. So, I have added 1 to my answer to compensate for that. However, my answer is failing for their input "5 5 N 4 10 N 8 5 N 8 8 N 6", which I don't understand how it can fail. I am having low confidence and want to know if I am doing anything wrong to find out the height of the tree here.
int result1 = 0;
int result2 = 0;
int MyHeight(Node *root)
{
if(root->left == NULL && root->right == NULL)
{
return 0;
}
if(root->left)
{
//cout<<"Executing root->left = data = "<<root->data<<endl;
result1 = MyHeight(root->left) + 1;
//cout<<"height -left --of .."<<root->data<<" = "<<result1<<endl;
}
if(root->right)
{
result2 = MyHeight(root->right) + 1;
//cout<<"right.height of .."<<root->data<<" = "<<result2<<endl;
}
if(result1 > result2)
return result1;
return result2;
}
int get_Height(Node* root)
{
// Your code here
//cout<<"root->data"<<root->data;
return MyHeight(root);
}
On what scenario, this implementation can fail? Can you draw a tree in the scenario where it will fail? I have debug it and I can't see what is going wrong there. It sounds like an invalid BST they have but I want to know if my implementation is correct or not. I cannot see that it is wrong actually.