Topics / Data Structures & Algorithms / Q25
Validate whether a binary tree is a binary search tree.
Short answer: Check every node against the allowed range inherited from its ancestors, not just its immediate children. This example rejects duplicates.
#include <stdint.h>
#include <stdbool.h>
struct tree {
int32_t key;
struct tree *left, *right;
};
bool valid_bst(const struct tree *r, int64_t low, int64_t high)
{
if (!r) return true;
if (r->key <= low || r->key >= high) return false;
return valid_bst(r->left, low, r->key) &&
valid_bst(r->right, r->key, high);
}
/* Call valid_bst(root, INT64_MIN, INT64_MAX). */
A value of 12 anywhere in the left subtree of root 10 is invalid, even if its immediate parent permits it. Time O(n), recursion space O(h). Use a wider bound type so INT32_MIN and INT32_MAX remain valid keys.