Trees and binary search trees · Exercise 35 of 100
Validate a binary search tree
In a binary search tree with distinct keys, every key in a node's left subtree must be smaller than that node's key, and every key on its right must be larger. Carry the allowed range down the tree, tightening the upper bound when you go left and the lower bound when you go right. This checks the ordering rules inherited from all ancestors.
Try it yourself
Root 20 has left child 8 and right child 32. Node 32 has left child 17 and right child 40. Which value falls outside the range allowed by its ancestors?
One-step hint
Carry both bounds as you descend. Taking the root's right link sets a lower bound that still applies when you later turn left.
Worked solution
- Both children of 20 are on the correct side. Every descendant of 32 must also exceed 20 because 32 is in the right subtree of 20.
- The left child of 32 must be between 20 and 32. Its value 17 is below the lower bound, while the right child 40 exceeds both 20 and 32.