Validate Binary Search Tree


Link: LeetCode - Validate Binary Search Tree


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:


Examples

Example 1:

Input: root = [2,1,3]
Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's right child 4 is less than 5 but in the wrong subtree.

Constraints


Intuition

We must ensure every node falls within a valid range:

We use a recursive function that carries valid min and max bounds and enforces this rule.


Approach: Recursive Bound Check


Java Code

class Solution {
    public boolean isValidBST(TreeNode root) {
        return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean validate(TreeNode node, long min, long max) {
        if (node == null) return true;

        if (node.val <= min || node.val >= max) return false;

        return validate(node.left, min, node.val) &&
               validate(node.right, node.val, max);
    }
}

Note: We use long instead of int for min/max to avoid edge case overflows (Integer.MIN_VALUE, Integer.MAX_VALUE).


Time & Space Complexity


Dry Run

For input:

     5
    / \
   1   4
      / \
     3   6

Conclusion

This method efficiently validates the BST property using a range-based DFS approach.
Alternate solutions using inorder traversal (iterative or recursive) are also possible but more error-prone due to tracking state.