Is this tree a valid BST? Why checking children isn't enough
Question
A support bot keeps ticket ids in a binary search tree (BST). In a BST, every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. Keys are distinct.
Write is_valid_bst(root). It returns True only for a valid BST. Each node has key, left and right.
good: 40 bad: 40
/ \ / \
25 60 25 60
/ \ / \
10 30 10 45In bad, every child is on the correct side of its parent. Why is it still not a BST?
class Node: def __init__(self, key, left=None, right=None): self.key, self.left, self.right = key, left, right def is_valid_bst(root): ...
Show hints (3)
- "LOOK FURTHER UP"
In
bad, 45 is larger than its parent 25. That part is fine. But 45 is also in the left subtree of 40. What must every key on that side of 40 be? - "CARRY A RANGE"
Pass each node the range its key must fall in. The root accepts anything. Going left, the upper limit becomes the parent's key. Going right, the lower limit does.
- "THE FAILING NODE"
For 45 the range is above 25 and below 40. 45 is outside it, so return
False. An empty subtree is always valid, so returnTrueforNone.
Show checked explanation
Comparing a node with its children is not enough. A key must fit every ancestor, not just its parent. So pass a range down the tree. Going left, the node's key becomes the upper limit. Going right, it becomes the lower limit. Every key must lie strictly inside its range. This is O(n) time.
class Node: def __init__(self, key, left=None, right=None): self.key, self.left, self.right = key, left, right def is_valid_bst(node, low=None, high=None): 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_valid_bst(node.left, low, node.key) and is_valid_bst(node.right, node.key, high)) good = Node(40, Node(25, Node(10), Node(30)), Node(60)) bad = Node(40, Node(25, Node(10), Node(45)), Node(60)) twice = Node(40, Node(40)) print(is_valid_bst(good), is_valid_bst(bad), is_valid_bst(twice))
True False False
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
In bad, each parent and child pair looks right: 10 < 25 < 45, and 25 < 40 < 60. A check that only compares a node with its children returns True. But 45 is in the left subtree of 40, so it must be smaller than 40. It isn't.
So each node needs the limits set by all its ancestors. The code carries them down as low and high. None means no limit on that side:
| node | low | high | key inside? |
|---|---|---|---|
| 40 | none | none | yes |
| 25 | none | 40 | yes |
| 10 | none | 25 | yes |
| 45 | 25 | 40 | no, 45 is not below 40 |
Going left sets high to the parent's key. Going right sets low. The other limit is passed on unchanged. That is how 45 gets the limit 40 from its grandparent. The search stops at 45 and returns False. Python's and stops at the first False, so 60 is never visited.
In twice, the left child 40 must be below 40, so it fails. Keys are distinct, so the comparisons are strict.
Each node is visited at most once, so the check is O(n) time. The recursion goes as deep as the tree is tall, so it uses O(h) stack for a tree of height h.
Common mistakes
- Comparing each node only with its children. That version returns
Trueforbad, because it only sees 45 > 25. - Writing
if low and node.key <= low. When the limit is 0,lowis falsy, so the test is skipped. A root 0 with a right child -5 then passes. - Failing only when
key < loworkey > high. Equal keys slip through:twice, with 40 under 40, is accepted although keys must be distinct. - Finding the largest key of the left subtree again at every node. The answer is correct, but on a chain of n nodes each node rescans everything below it. That is O(n²).
Follow-up questions
- "Can you solve it with an inorder traversal instead?" Yes. Inorder visits left, node, right. In a valid BST it gives the keys in strictly increasing order. Keep the previous key and fail when a key is not larger. For
badthe order is 10, 25, 45, 40, 60, and the 40 after 45 fails. - "Duplicates are allowed now, and they go to the right subtree. What changes?" The rule becomes: left keys are smaller, right keys are larger or equal. So a key may equal its lower limit, but not its upper one. Change the first test to
node.key < lowand keepnode.key >= high. - "The tree is a chain of 100,000 nodes. Does your code still work?" No. The recursion goes 100,000 calls deep. Python's default recursion limit is 1,000, so you get
RecursionError. Use a loop with an explicit stack of(node, low, high)tuples.
What a strong answer covers
Shows a concrete tree where parent and child checks pass but the BST is broken. Carries a range from the ancestors and uses strict comparisons. Asks about duplicates first. States O(n) time and O(h) stack, and knows the inorder version.
Open in interactive practice deck →