Understanding the Problem
We are given a binary tree, and our task is to determine whether it satisfies the properties of a Binary Search Tree (BST). In a BST, for every node:
- All nodes in its left subtree must contain values strictly less than the node’s value.
- All nodes in its right subtree must contain values strictly greater than the node’s value.
This rule must be true not just at the root but recursively for all subtrees.
Step-by-Step Solution with Example
Step 1: Recognize the base case
If the tree is empty (i.e., the root node is null
), it is considered a valid BST by definition because there are no violations possible.
Step 2: Use recursion with value boundaries
For each node, we must verify that its value lies within a valid range. Initially, the root can have any value. But as we go down the tree:
- The left child must be in the range
(min, node.val)
.
- The right child must be in the range
(node.val, max)
.
Step 3: Apply to a simple valid BST
2
/ 1 3
We start at node 2:
- 1 is to the left of 2, and 1 < 2 ✅
- 3 is to the right of 2, and 3 > 2 ✅
Both children are leaf nodes, so their subtrees are trivially valid. The whole tree is a valid BST.
Step 4: Detect a violation in subtree
5
/ 1 4
/ 3 6
At first glance, 4 is greater than 5’s left child (1) and less than 5. But dig deeper:
- Node 3 is in the right subtree of 5 but 3 < 5 ❌
This violates the BST rule. So, even though the tree looks locally correct, it's not a valid BST.
Step 5: Consider deeper boundary checks
10
/ 5 15
/ 6 20
Node 6 is in the right subtree of 10 but has value 6 < 10 ❌
To detect such violations, we must pass down min and max boundaries during recursion. Here, node 6 violates the range (10, 15).
Step 6: A perfectly balanced valid BST
8
/ 4 12
/ / 2 6 10 14
This tree follows all the BST rules:
- Each node places smaller values on the left and greater values on the right.
- This rule holds true recursively for all nodes.
Hence, it is a valid BST ✅
Edge Cases
- Empty Tree: Considered a valid BST. No nodes = no violations.
- Single Node: Always valid as there are no children to compare.
- Duplicate Values: Not allowed in a strict BST. If duplicates are allowed, rules must be clearly defined (e.g., duplicates on left or right).
- Negative and large values: Our range checking should support full integer range.
Finally
To accurately verify whether a tree is a BST, we need to go beyond local comparisons and consider the valid range of values that each node can take, as defined by its ancestors. This is done by recursively checking each node within its permissible min and max boundaries. With this approach, both shallow and deep violations can be caught effectively.
Keep in mind that even a tree that appears valid visually may have subtle rule violations deep in the structure—always think in terms of ranges, not just parent-child values.
Comments
Loading comments...