Knowledge Guide
HomeDSATrees

medium Validate Binary Search Tree

Problem Statement

Determine if a given binary tree is a binary search tree (BST). In a BST, for each node:

Examples

Example 1:

Image
Image

Example 2:

Image
Image

Example 3:

Image
Image

Constraints:

Try it yourself

Try solving this question here:

✅ Solution Validate Binary Search Tree

Problem Statement

Determine if a given binary tree is a binary search tree (BST). In a BST, for each node:

  • All nodes to its left have values less than the node's value.
  • All nodes to its right have values greater than the node's value.

Examples

Example 1:

  • Input: [5,3,7]
  • Expected Output: true
  • Justification: The left child of the root (3) is less than the root, and the right child of the root (7) is greater than the root. Hence, it's a BST.
Image
Image

Example 2:

  • Input: [5,7,3]
  • Expected Output: false
  • Justification: The left child of the root (7) is greater than the root, making it invalid.
Image
Image

Example 3:

  • Input: [10,5,15,null,null,12,20]
  • Expected Output: true
  • Justification: Each subtree of the binary tree is a valid binary search tree. So, a whole binary tree is a valid binary search tree.
Image
Image

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231</sup <= Node.val <= 231</sup - 1

Solution

In essence, to validate if a given binary tree is a binary search tree (BST), we employ a recursive approach that checks the validity of each node by comparing its value with a permissible range. This range is determined by the node's ancestors, ensuring every node meets the BST property. Initially, the root node can take any value between negative infinity and positive infinity. As we traverse down the tree, we update this range based on the current node's value.

Detailed Breakdown:

  1. Recursion:
    • For each node in the binary tree, we validate its value against a permissible range. If the value does not lie within this range, the tree is not a BST.
    • The range for any node is influenced by its ancestors, ensuring that every node, even those deep in the tree, satisfies the BST condition.
  2. Base Case:
    • If the node we are inspecting is null (i.e., we've reached a leaf node), we return true since a null subtree is always a BST by definition.
  3. Recursive Step:
    • Compare the node's value against its permissible range. If it's not within the range, return false.
    • If it is within range, we recursively check the left and right children, but with updated permissible ranges.
  4. Implementation:
    • Initially, the root node's range is set to (-Infinity, +Infinity).
    • For every left child, the upper limit of its permissible range is updated to the current node's value. Similarly, for every right child, the lower limit is updated to the current node's value.

Algorithm Walkthrough

For the tree [10,5,15,null,null,12,20]:

  • Start with the root, range = (-Infinity, +Infinity)
    • Node 10 is within the range.
  • Move to the left child, range = (-Infinity, 10)
    • Node 5 is within the range.
  • Move to the right child of root, range = (10, +Infinity)
    • Node 15 is within the range.
  • Move to the left child of 15, range = (10, 15)
    • Node 12 is within the range.
  • Move to the right child of 15, range = (15, +Infinity)
    • Node 20 is within the range.
  • return true, as the next left node is null.

Code

java
// class TreeNode {
//     int val;
//     TreeNode left;
//     TreeNode right;
//     TreeNode(int x) { val = x; }
// }

public class Solution {

  // Main method to check if a tree is a BST
  public boolean isValidBST(TreeNode root) {
    // Initially, the range is set to the largest and smallest possible values
    return isValidBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
  }

  // Helper method that checks the node value against a range
  private boolean isValidBSTHelper(TreeNode node, long min, long max) {
    // Null nodes are always BST
    if (node == null) return true;

    // Node value should be strictly within the min and max
    if (node.val <= min || node.val >= max) return false;

    // Recursively check left (with updated max) and right (with updated min)
    return (
      isValidBSTHelper(node.left, min, node.val) &&
      isValidBSTHelper(node.right, node.val, max)
    );
  }

  // Test the solution with the examples
  public static void main(String[] args) {
    Solution sol = new Solution();

    TreeNode example1 = new TreeNode(5);
    example1.left = new TreeNode(3);
    example1.right = new TreeNode(7);
    System.out.println(sol.isValidBST(example1)); // true

    TreeNode example2 = new TreeNode(5);
    example2.left = new TreeNode(7);
    example2.right = new TreeNode(3);
    System.out.println(sol.isValidBST(example2)); // false

    TreeNode example3 = new TreeNode(10);
    example3.left = new TreeNode(5);
    example3.right = new TreeNode(15);
    example3.right.left = new TreeNode(12);
    example3.right.right = new TreeNode(20);
    System.out.println(sol.isValidBST(example3)); // false
  }
}

Complexity Analysis

  • Time Complexity: O(n) - We traverse each node once.
  • Space Complexity: O(h) - The space is determined by the height of the tree due to recursive calls. In the worst case (skewed tree), it's O(n), while in the best case (balanced tree), it's O(log n).
🤖 Don't fully get this? Learn it with Claude

Stuck on Validate Binary Search Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Validate Binary Search Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Validate Binary Search Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Validate Binary Search Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Validate Binary Search Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes