Validate if Tree is BST in DSA Typescript - Time & Space Complexity
We want to know how long it takes to check if a tree follows the rules of a Binary Search Tree (BST).
How does the time needed grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
function isBST(node: TreeNode | null, min: number = -Infinity, max: number = Infinity): boolean {
if (node === null) return true;
if (node.val <= min || node.val >= max) return false;
return isBST(node.left, min, node.val) && isBST(node.right, node.val, max);
}
This code checks if a binary tree is a BST by making sure each node's value fits between allowed minimum and maximum limits.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
As the tree grows, the function visits every node once to check its value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to check the tree grows in a straight line with the number of nodes.
[X] Wrong: "The function only checks some nodes, so it runs faster than O(n)."
[OK] Correct: The function must visit every node to be sure the whole tree follows BST rules, so it always checks all nodes.
Understanding this helps you explain how to verify tree properties efficiently, a common skill in coding interviews.
"What if we used an in-order traversal to check the BST property instead? How would the time complexity change?"