Let's say you have the following tree:
20
/ \
10 30
/
15
and start at the root with your code:
1 int validate(node *root) {
2 if(root==NULL) return 1;
3 else if(root->lchild!=NULL && (root->lchild)->data >=root->data) return 0;
4 else if(root->rchild!=NULL && (root->rchild)->data <=root->data) return 0;
5 validate(root->lchild);
6 validate(root->rchild);
7 return 1;
8 }
Now the first three if
statements (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 validate
and 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 if
things since they're useless following a return, and I'm not a big fan of using the variable root
in 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):
int validate (node *testNode) {
// Terminal case, empty sub-tree is valid.
if (testNode == NULL)
return 1;
// Left node >= current means invalid
if (testNode->lchild != NULL)
if (testNode->lchild->data >= testNode->data)
return 0;
// Right node <= current means invalid
if (testNode->rchild != NULL)
if (testNode->rchild->data <= testNode->data)
return 0;
// Invalid entire left subtree means invalid.
if (! validate (testNode->lchild))
return 0;
// Otherwise return state of entire right subtree.
return validate (testNode->rchild);
}
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 >=
.