Is anyone able to tell me why this doesn't work as a recursive function to find whether a binary tree is height balanced using non-tail recursion? I was provided with everything except the final if statement, so everything else cannot be altered.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
template<class T>
int BST<T>::is_perfectly_balanced(BSTNode<T> *p) const
{
if (p == 0) {
return 0;
}
else {
int left = is_perfectly_balanced(p->left);
int right = is_perfectly_balanced(p->right);
if(abs(left-right) <= 1)
return 0;
return -1;
}
}
|
This is the output I receive, the proper answer is in the brackets and below is the answer my program outputs.
Empty tree is height balanced? (Yes)
Yes.
Single node is height balanced? (Yes)
Yes.
Linked list of two nodes is height balanced? (Yes)
Yes.
Linked list of three nodes is height balanced? (No)
Yes.
Full binary tree of three nodes (plus one node) is height balanced? (Yes)
Yes.
Full binary tree of three nodes (plus two nodes) is height balanced? (No)
Yes.
Any help would be appreciated, thanks!