Write a function to determine whether a given binary tree of distinct integers is a

valid binary search tree. Assume that each node contains a pointer to its left child, a

pointer to its right child, and an integer, but not a pointer to its parent. You may use

any language you like.

Good Answer: Note that it’s not enough to write a recursive function that just checks

if the left and right nodes of each node are less than and greater than the current

node (and calls that recursively). You need to make sure that all the nodes of the

subtree starting at your current node are within the valid range of values allowed by

the current node’s ancestors. Therefore you can solve this recursively by writing a

helper function that accepts a current node, the smallest allowed value, and the

largest allowed value for that subtree. An example of this is the following (in Java):

1: boolean isValid(Node root) {

2: return isValidHelper(root, Integer.MIN_VALUE,

` 3: Integer.MAX_VALUE);`

` 4: }`

5: boolean isValidHelper(Node curr, int min, int max) {

6: if (curr.left != null) {

7: if (curr.left.value < min ||

` 8: !isValidHelper(curr.left, min, curr.value))`

9: return false;

` 10: }`

11: if (curr.right != null) {

12: if (curr.right.value > max ||

` 13: !isValidHelper(curr.right, curr.value, max))`

14: return false;

` 15: }`

16: return true;

` 17: }`

The running time of this algorithm is O(n).