Validating Binary Search Trees with Recursive Boundary Checks

Valid Binary Search Tree (BST) properties:

  • A node's left subtree contains only nodes with values less than the node's value.
  • A node's right subtreee contains only nodes with values greater than the node's value.
  • Both left and right subtrees must also be valid BSTs.

Example 1:

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

Example 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: Root value is 5, but right child value is 4.

Approach

Recursive traversal with boundary cnostraints provides an efficient solution for BST validation.

Implementation

class TreeNode {
    int value;
    TreeNode leftChild;
    TreeNode rightChild;
    TreeNode() {}
    TreeNode(int val) { value = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        value = val;
        leftChild = left;
        rightChild = right;
    }
}

class Solution {
    public boolean isValidBST(TreeNode root) {
        return validateNode(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    private boolean validateNode(TreeNode currentNode, long minBound, long maxBound) {
        if (currentNode == null) return true;
        
        if (currentNode.value <= minBound || currentNode.value >= maxBound) {
            return false;
        }
        
        return validateNode(currentNode.leftChild, minBound, currentNode.value) 
            && validateNode(currentNode.rightChild, currentNode.value, maxBound);
    }
}

Tags: Binary Search Tree tree validation Recursive Algorithms Java Implementation

Posted on Sun, 07 Jun 2026 17:20:19 +0000 by dino345