Here is the code that I have written to validate a BST.
Is it correct? If not, how would I do this?
int validate(node *root)
{
if(root==NULL) return 1;
else if(root->lchild!=NULL && (root->lchild)->data >=root->data) return 0;
else if(root->rchild!=NULL && (root->rchild)->data <=root->data) return 0;
validate(root->lchild);
validate(root->rchild);
return 1;
}
Let’s say you have the following tree:
and start at the root with your code:
Now the first three
ifstatements (lines 2 through 4) don’t “fire” at the root node because the first two levels of the tree are okay (the left node is less than 20 and the right node is greater than 20). So you then try to validate the left subtree (the node containing 10) by a recursive call at line 5.In that call, it’s not okay since its left node (15) is larger than it is and line 3 will return zero to indicate it’s bad.
However, because you’ve called
validateand thrown away the return value, it simply carries on to line 6 then eventually returns 1 on that final line 7, even though the tree is not valid.What you need to do is to to pass up the lower level results to the upper levels so that they can be acted upon.
You can also get rid of those
else ifthings since they’re useless following a return, and I’m not a big fan of using the variablerootin this case since it’s only root at the top level of the recursion (it may confuse some).I’d go with something like (with appropriate comments):
You may also want to think about whether you want duplicate values in your tree. If you do, the comparisons should be
<and>rather than<=and>=.