, , . , :
(10
(7
nil
(20 nil nil)
)
nil
)
(7) (10) (7 <= 10), (20) 7 (20 >= 7). BST ( ), 20 10.
To fix this, you can do a workaround by passing extra arguments that specify a valid interval for the subtree.
bool IsBST(const node_t* tree, int lower_bound, int upper_bound) {
if (tree == NULL) return true;
if (tree->value <= lower_bound) return false;
if (tree->value >= upper_bound) return false;
if (!IsBST(tree->left, lower_bound, tree->value))
return false;
if (!IsBST(tree->right, tree->value, upper_bound))
return false;
return true;
}
Note that, while maintaining the original valid interval, the function will find that the value 20 is not valid at this position, since it is not inside (7, 10). The first call must be made at infinite intervals, for example:
IsBST(tree, INT_MIN, INT_MAX);
Hope this helps.
source
share