Static variables preserve their values between function calls.
If they are initialized as part of the declaration, as in
static treeNode *prev=NULL;
, the initialization happens exactly once.
So for instance, if you have f:
void f(int n) {
static int x = 4;
if (!n) {
printf(" : ");
return;
}
x += 2;
printf("%d ", x);
f(n - 1);
printf("(%d) ", x);
}
Then f(3)
will print 6 8 10 (10) (10) (10)
. The static variable is used both to pass a value to the recursive call and to get a value back. In the case of the BST check, that's being used to find the value of the rightmost element of the left subtree.
But there are a couple issues with doing it that way.
f(3); putchar('\n'); f(3);
prints
6 8 10 (10) (10) (10)
12 14 16 (16) (16) (16)
because we forgot to reset the static variable between non-recursive calls. And if we call f(3)
from two different threads at the same time, the same static variable is used in both calls, and there's no telling what order the numbers will come out in.
The logic behind isBSTtree is to do a left to right traversal, keeping track of the greatest element seen thus far, and indicates failure if it the greatest element seen to the left of a node is greater than the node's value. So a better way to do it would be:
int isBSTaux(treeNode *T, treeNode **prev) {
if(!T) return 1;
if (!isBSTaux(T->left, prev)) return 0;
if (*prev && (*prev)->value > T->value) return 0;
*prev = T;
return isBSTaux(T->right, prev);
}
int isBSTtree(treeNode *root) {
treeNode *prev = NULL;
return isBSTaux(root, &prev);
}
Each call to isBSTtree gets its own copy of prev, which is reinitialized each time through, and is not shared between different calls.
(Which is not to say that static local variables don't have their uses; they just aren't the right choice in this particular case.)