Validating BST

Time Complexity: O(n)

Traverses through all the nodes

class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, null, null);
    }
    
    private boolean isValidBST(TreeNode root, Integer min, Integer max) {
        // Reached the leaf node, which means property of BST is satisfied all along
        if(root == null) {
            return true;
        }
        
        // Invalidating condition for BST
        // left subtree value should be less than root value
        // right subtree value should be greater than root value
        if((min!=null && root.val >= min) || (max!=null && max <= root.val)) {
            return false;
        }

        // Iterate it over left and right subtrees
        return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
    }
}

Last updated

Was this helpful?