Sub topic 8
The binary search tree property
This chapter assumes you know basic tree vocabulary (root, child, leaf, height), how a binary tree is stored as linked nodes, and the three depth-first traversals. It also assumes you can read recursive Python and use Big-O notation. Search, insertion, and deletion come in later chapters. Here we pin down what the ordering property says, how to check it, and where people get it wrong.
What the property says
A binary search tree (BST) is a binary tree in which every node's key obeys an ordering rule relative to its whole subtrees, not only its immediate children:
- Every key in the node's left subtree is smaller than the node's key.
- Every key in the node's right subtree is larger than the node's key.
- Both subtrees are themselves binary search trees.
The rule is recursive. If the left and right subtrees are valid BSTs and the root satisfies the two inequalities against all keys below it, the whole tree is a valid BST.
The version above assumes distinct keys, which is the usual GATE convention. If a question allows duplicates, it will say where they go. Common choices are "left subtree keys are less than or equal" or "right subtree keys are greater than or equal". The code in this tutorial ignores duplicates on insertion, so each key appears at most once.
In this tree, 6 sits in the right subtree of 3 and in the left subtree of 8. It must be greater than 3 and less than 8, and it is.
The most common mistake: checking only the parent
A frequent error is to believe the property is local: "each node is larger than its left child and smaller than its right child". That condition is necessary but not sufficient. Consider this tree.
Node 5 has right child 12, and 12 is greater than 5. Node 10 has left child 5 (smaller) and right child 15 (larger). Every parent-child pair looks fine. Yet 12 lies in the left subtree of 10 and is larger than 10, so the tree is not a BST. A search for 12 would go right from 10 and never find it.
Each node therefore carries an allowed interval inherited from all its ancestors. A validity check must pass that interval downward.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def is_bst(node, low=None, high=None):
"""True if every key lies strictly between low and high."""
if node is None:
return True
if low is not None and node.key <= low:
return False
if high is not None and node.key >= high:
return False
return (is_bst(node.left, low, node.key) and
is_bst(node.right, node.key, high))
# The invalid tree from the diagram above
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.right = Node(12)
print(is_bst(root)) # False
# Fix it by replacing 12 with 7
root.left.right.key = 7
print(is_bst(root)) # TrueGoing left, the current key becomes the new upper bound. Going right, it becomes the new lower bound. The check visits each node once, so it runs in O(n) time. The recursion depth equals the tree height.
Consequences of the property
Search direction is forced
At any node, comparing the target with the node's key rules out an entire subtree. If the target is smaller, everything in the right subtree is larger than the node and so larger than the target. The target can only be on the left. This is why search follows one root-to-leaf path instead of exploring the tree.
Minimum and maximum
The smallest key is at the leftmost node, reached by following left pointers until there is none. The largest key is at the rightmost node. Neither is necessarily a leaf: the minimum has no left child but can have a right child.
def minimum(node):
while node.left:
node = node.left
return node
def maximum(node):
while node.right:
node = node.right
return nodeIn the first diagram, the minimum is 1 (a leaf), but the maximum is 14. If 14 had a left child 12, the maximum would still be 14, a node with a child.
Inorder traversal is sorted
Inorder traversal visits the left subtree, then the node, then the right subtree. By the property, that is "everything smaller, then this key, then everything larger", applied recursively. Inorder on the first diagram gives 1, 3, 6, 8, 10, 14. The next chapters build on this fact, and it gives a second validity test: a binary tree with distinct keys is a BST exactly when its inorder sequence is strictly increasing.
Preorder and postorder are not sorted
Preorder on the first diagram gives 8, 3, 1, 6, 10, 14, which is not sorted. Only inorder has the sorted guarantee. Preorder does have a useful property for BSTs, though. Because the root comes first, inserting the keys of a preorder sequence into an empty BST, one at a time, rebuilds the same tree.
Shape depends on insertion order
The property constrains where keys may go relative to each other, but it does not fix the tree's shape. The same set of keys gives many different BSTs, depending on the order of insertion.
| Insertion order | Resulting shape | Height |
|---|---|---|
| 4, 2, 6, 1, 3, 5, 7 | Perfect tree | 2 |
| 1, 2, 3, 4, 5, 6, 7 | Right-skewed chain | 6 |
| 7, 6, 5, 4, 3, 2, 1 | Left-skewed chain | 6 |
| 4, 2, 1, 3, 6, 5, 7 | Also perfect | 2 |
The seven keys 1 to 7 can produce shapes anywhere from height 2 to height 6. Every one of them is a valid BST with the same sorted inorder sequence. This variability is the reason the cost of BST operations depends on height and not on the number of keys alone. A later chapter on cost and height develops this, and the last chapter shows how rotations in AVL trees prevent the bad shapes.
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
for order in ([4, 2, 6, 1, 3, 5, 7], [1, 2, 3, 4, 5, 6, 7]):
root = None
for k in order:
root = insert(root, k)
print(order, "height", height(root))
# [4, 2, 6, 1, 3, 5, 7] height 2
# [1, 2, 3, 4, 5, 6, 7] height 6Here an empty tree has height -1 and a single node has height 0. This is the convention used with the formulas in the counting chapter. Some textbooks count height in nodes, which adds 1. Always check which convention a GATE question uses.
Worked example: is this a BST?
A question gives the preorder sequence 50, 30, 20, 40, 70, 60, 80 and asks whether it can be the preorder of a BST.
- The root is 50. The keys after it that are less than 50 (30, 20, 40) must form the left subtree, and the keys greater than 50 (70, 60, 80) must form the right subtree.
- In the preorder, all smaller keys must come before all larger keys. Here 30, 20, 40 come first and 70, 60, 80 follow, so the split is consistent.
- Repeat inside each part. For 30, 20, 40: root 30, left 20, right 40. For 70, 60, 80: root 70, left 60, right 80.
The sequence is valid, and the tree is perfect with height 2. Now take 50, 30, 70, 20. The root is 50 and the left subtree should hold the keys less than 50, but 20 appears after 70 (a right-subtree key). A smaller key after a larger one breaks the split, so this cannot be the preorder of a BST.
Common errors
- Checking only parent and child, as shown above. Always compare against all ancestors.
- Assuming the minimum is a leaf. It has no left child but may have a right child.
- Assuming a BST is balanced or complete. The property says nothing about shape.
- Treating any traversal as sorted. Only inorder is.
- Forgetting the duplicate rule when the question defines one.
Exercise
A binary tree has root 20, left child 10, and right child 30. Node 10 has a right child 25. Node 30 has no children. Is it a BST? Give the reason, and state its inorder sequence.
Show answer
It is not a BST. Node 25 lies in the left subtree of 20 but is larger than 20, even though 25 is larger than its parent 10. The inorder sequence is 10, 25, 20, 30, which is not increasing.
Exercise
Seven distinct keys are inserted into an empty BST in the order 40, 20, 10, 30, 60, 50, 70. What is the height of the tree (empty tree = -1), and what is the postorder sequence?
Show answer
The tree has root 40, left child 20 (children 10 and 30), and right child 60 (children 50 and 70). It is perfect, so the height is 2. Postorder visits left subtree, right subtree, then the node: 10, 30, 20, 50, 70, 60, 40.
Exercise
Which statement is true for every BST with distinct keys: (a) the maximum key is a leaf, (b) the minimum key has no left child, (c) preorder is sorted, (d) the root is the median key?
Show answer
Only (b). The minimum is the leftmost node, so it has no left child. The maximum may have a left child, preorder is not generally sorted, and the root's rank depends on insertion order.