Skip to Content

Validate Binary Search Tree (BST)

Home | Coding Interviews | Simple Data Structures | Validate Binary Search Tree (BST)

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

The left subtreeof a node contains only nodes with keys less than the node's key.

The right subtree of a node contains only nodes with keys greater than the node's key.

Both the left and right subtrees must also be binary search trees.

class Solution {
    public boolean isValidBST(TreeNode root) {
        
        return checker( -INF, INF, root);
    }
    
    private boolean checker( long lower, long upper, TreeNode node ){
        
        if( node == null ){
            return true;
        }
        
        if( (lower < node.val) && ( node.val < upper ) ){
            return checker(lower, node.val, node.left) && checker(node.val, upper, node.right);
        }
        
        return false;
    }
    
    private long INF = Long.MAX_VALUE;

}

Posted by Jamie Meyer 4 months ago

Related Problems

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Given the root of a binary tree, flatten the tree into a "linked list":

The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.

The "linked list" should be in the same order as a pre-order traversal of the binary tree.

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

You are given two binary trees root1 and root2.

Imagine the trees are layed ontop of each other. The merged nodes will have the sum of the values of the original nodes. If one or the other is null, treat the null node as if it had a value of 0.

Return the merged tree.