Bird
Raised Fist0
DSA Javaprogramming

Validate if Tree is BST in DSA Java

Choose your learning style10 modes available
Mental Model
A binary search tree (BST) has nodes arranged so that left children are smaller and right children are larger than the parent node.
Analogy: Imagine a family tree where every child on the left side is younger than their parent, and every child on the right side is older, keeping the order clear and easy to check.
    4
   / \
  2   6
 / \ / \
1  3 5  7
Dry Run Walkthrough
Input: Tree: 4 -> 2, 6; 2 -> 1, 3; 6 -> 5, 7
Goal: Check if the tree follows BST rules: left < parent < right for every node
Step 1: Start at root 4, set allowed range (-∞, +∞)
4 (range: -∞ to +∞)
Why: Root can be any value, so start with full range
Step 2: Check left child 2 with range (-∞, 4)
2 (range: -∞ to 4)
Why: Left child must be less than parent 4
Step 3: Check left child of 2: 1 with range (-∞, 2)
1 (range: -∞ to 2)
Why: Left child of 2 must be less than 2
Step 4: Check right child of 2: 3 with range (2, 4)
3 (range: 2 to 4)
Why: Right child of 2 must be greater than 2 and less than 4
Step 5: Check right child 6 with range (4, +∞)
6 (range: 4 to +∞)
Why: Right child must be greater than parent 4
Step 6: Check left child of 6: 5 with range (4, 6)
5 (range: 4 to 6)
Why: Left child of 6 must be greater than 4 and less than 6
Step 7: Check right child of 6: 7 with range (6, +∞)
7 (range: 6 to +∞)
Why: Right child of 6 must be greater than 6
Result:
Tree is a valid BST
Annotated Code
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}

public class ValidateBST {
    public static boolean isValidBST(TreeNode root) {
        return helper(root, null, null);
    }

    private static boolean helper(TreeNode node, Integer lower, Integer upper) {
        if (node == null) return true;

        int val = node.val;
        if (lower != null && val <= lower) return false;  // value must be greater than lower bound
        if (upper != null && val >= upper) return false;  // value must be less than upper bound

        if (!helper(node.left, lower, val)) return false;  // left subtree must be less than current node
        if (!helper(node.right, val, upper)) return false;  // right subtree must be greater than current node

        return true;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(6);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(5);
        root.right.right = new TreeNode(7);

        System.out.println(isValidBST(root) ? "Tree is a valid BST" : "Tree is NOT a valid BST");
    }
}
if (node == null) return true;
base case: empty subtree is valid
if (lower != null && val <= lower) return false;
check if current node violates lower bound
if (upper != null && val >= upper) return false;
check if current node violates upper bound
if (!helper(node.left, lower, val)) return false;
recursively validate left subtree with updated upper bound
if (!helper(node.right, val, upper)) return false;
recursively validate right subtree with updated lower bound
OutputSuccess
Tree is a valid BST
Complexity Analysis
Time: O(n) because we visit each node once to check BST property
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Compared to inorder traversal method which also takes O(n), this method uses range checks and is straightforward to implement
Edge Cases
Empty tree
Returns true because an empty tree is a valid BST
DSA Java
if (node == null) return true;
Single node tree
Returns true because one node always satisfies BST rules
DSA Java
if (node == null) return true;
Tree with duplicate values
Returns false because BST does not allow duplicates on left or right
DSA Java
if (lower != null && val <= lower) return false;
When to Use This Pattern
When you need to check if a binary tree follows ordering rules for all nodes, use range limits to validate each node's value recursively.
Common Mistakes
Mistake: Only checking immediate children without considering the full allowed value range
Fix: Pass down lower and upper bounds to each recursive call to ensure all descendants respect BST rules
Summary
Checks if a binary tree satisfies the binary search tree property using value ranges.
Use when you want to confirm a tree is a BST before performing BST-specific operations.
The key insight is to track allowed value ranges for each node, not just compare with immediate parent.

Practice

(1/5)
1. What is the main property that defines a Binary Search Tree (BST)?
easy
A. For each node, all nodes in the left subtree are smaller and all nodes in the right subtree are larger
B. Each node has exactly two children
C. All nodes have unique values but no order is required
D. The tree is always balanced

Solution

  1. Step 1: Understand BST property

    A BST requires that for every node, values in the left subtree are smaller and values in the right subtree are larger.
  2. Step 2: Compare options with BST definition

    For each node, all nodes in the left subtree are smaller and all nodes in the right subtree are larger correctly states this property, while others describe different tree characteristics.
  3. Final Answer:

    For each node, all nodes in the left subtree are smaller and all nodes in the right subtree are larger -> Option A
  4. Quick Check:

    BST property = For each node, all nodes in the left subtree are smaller and all nodes in the right subtree are larger [OK]
Hint: Remember BST means left < node < right [OK]
Common Mistakes:
  • Confusing BST with balanced tree
  • Thinking all nodes must have two children
  • Ignoring the ordering property
2. Which of the following Java method signatures is correct to check if a binary tree is a BST?
easy
A. public int isBST(Node root, int min, int max)
B. public boolean isBST(Node root, int min, int max)
C. public void isBST(Node root)
D. public boolean isBST(Node root, Node min, Node max)

Solution

  1. Step 1: Identify correct return type and parameters

    Checking BST returns true/false, so return type should be boolean. Also, min and max values are needed as integers to validate node values.
  2. Step 2: Match method signature

    public boolean isBST(Node root, int min, int max) matches this: boolean return type and int min, max parameters. Others have wrong return types or parameter types.
  3. Final Answer:

    public boolean isBST(Node root, int min, int max) -> Option B
  4. Quick Check:

    Return boolean with int min/max params [OK]
Hint: Use boolean return and int min/max for range checks [OK]
Common Mistakes:
  • Using void return type for a check method
  • Using Node type for min/max instead of int
  • Returning int instead of boolean
3. What will be the output of the following code snippet?
class Node {
  int val;
  Node left, right;
  Node(int v) { val = v; left = right = null; }
}

public class Test {
  static boolean isBST(Node root, int min, int max) {
    if (root == null) return true;
    if (root.val <= min || root.val >= max) return false;
    return isBST(root.left, min, root.val) && isBST(root.right, root.val, max);
  }

  public static void main(String[] args) {
    Node root = new Node(10);
    root.left = new Node(5);
    root.right = new Node(15);
    root.left.left = new Node(1);
    root.left.right = new Node(12);
    System.out.println(isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE));
  }
}
medium
A. Runtime exception
B. true
C. Compilation error
D. false

Solution

  1. Step 1: Trace the tree nodes and BST conditions

    The node with value 12 is in the left subtree of 10 but greater than 10, violating BST property.
  2. Step 2: Check isBST calls

    When checking root.left.right (12), it fails the condition root.val <= min or root.val >= max because 12 >= 10 is true, so returns false.
  3. Final Answer:

    false -> Option D
  4. Quick Check:

    Node 12 violates BST rule, so false [OK]
Hint: Check if any left child > root or right child < root [OK]
Common Mistakes:
  • Ignoring subtree value ranges
  • Assuming all nodes in left subtree are less than root only
  • Not updating min/max during recursion
4. Identify the bug in this BST validation code snippet:
boolean isBST(Node root) {
  if (root == null) return true;
  if (root.left != null && root.left.val > root.val) return false;
  if (root.right != null && root.right.val < root.val) return false;
  return isBST(root.left) && isBST(root.right);
}
medium
A. It does not handle null root properly
B. It uses wrong comparison operators for left and right children
C. It does not check the entire subtree values, only immediate children
D. It should return int instead of boolean

Solution

  1. Step 1: Analyze the checks performed

    The code only compares root with its immediate left and right children, not the entire subtree.
  2. Step 2: Understand BST validation requirement

    BST validation requires all nodes in left subtree < root and all in right subtree > root, not just immediate children.
  3. Final Answer:

    It does not check the entire subtree values, only immediate children -> Option C
  4. Quick Check:

    Check full subtree ranges, not just children [OK]
Hint: Check full subtree ranges, not just direct children [OK]
Common Mistakes:
  • Only comparing immediate children values
  • Ignoring recursive min/max range checks
  • Assuming local checks are enough
5. Given a binary tree, which approach correctly validates if it is a BST considering edge cases like duplicate values and integer limits?
hard
A. Use min and max integer range parameters updated during recursion
B. Use in-order traversal to check if values are strictly increasing
C. Check only immediate children values recursively
D. Compare each node with root only, ignoring subtrees

Solution

  1. Step 1: Understand edge cases in BST validation

    Duplicates and integer limits require careful range checks, not just value comparisons.
  2. Step 2: Evaluate approaches

    Using min and max parameters updated during recursion correctly enforces BST property for all nodes and handles edge cases.
  3. Final Answer:

    Use min and max integer range parameters updated during recursion -> Option A
  4. Quick Check:

    Range checks with min/max handle edge cases [OK]
Hint: Use min/max range checks recursively for full validation [OK]
Common Mistakes:
  • Ignoring duplicates or equal values
  • Not updating min/max during recursion
  • Only checking immediate children
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard