Lesson 57 of 73 2 min

Problem: Validate Binary Search Tree

Learn how to correctly validate BST properties using range boundaries in O(n).

Problem Statement

Given the root of a binary tree, determine if it is a valid Binary Search Tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Approach: Recursive Range Validation

A common mistake is only checking if a node is larger than its direct left child and smaller than its direct right child. You must ensure every node in the left subtree is smaller than the parent.

  1. Helper Function: Use a recursive function validate(node, min, max).
  2. Boundaries:
    • When moving left, update the max boundary to the current node's value.
    • When moving right, update the min boundary to the current node's value.
  3. Check: If node.val <= min or node.val >= max, return false.

Java Implementation

public boolean isValidBST(TreeNode root) {
    return validate(root, null, null);
}

private boolean validate(TreeNode node, Integer min, Integer max) {
    if (node == null) return true;
    
    if ((min != null && node.val <= min) || (max != null && node.val >= max)) {
        return false;
    }
    
    return validate(node.left, min, node.val) && 
           validate(node.right, node.val, max);
}

Complexity Analysis

  • Time Complexity: $O(n)$.
  • Space Complexity: $O(h)$ for the recursion stack.

Interview Tips

  • Mention the In-order Traversal trick: A BST's in-order traversal results in a sorted list. You can validate it by checking if the sequence is strictly increasing.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.