#98

Validate Binary Search Tree

Medium
TreeDepth-First SearchBinary Search TreeBinary TreeTree TraversalRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal approach uses a recursive function that checks each node's value against a range defined by its ancestors. This avoids the need to store all values and checks the BST properties in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a helper function that takes a node and a range (min and max values).
  2. 2Step 2: For each node, check if its value is within the range.
  3. 3Step 3: Recursively check the left subtree with updated max and the right subtree with updated min.
solution.py15 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8def isValidBST(root):
9    def validate(node, low=float('-inf'), high=float('inf')):
10        if not node:
11            return True
12        if not (low < node.val < high):
13            return False
14        return validate(node.left, low, node.val) and validate(node.right, node.val, high)
15    return validate(root)

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1A valid BST must have all left descendants less than the node and all right descendants greater.
  • 2Recursive validation can be more efficient than storing values for comparison.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.