Question

link

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

Assume a BST is defined as follows:

  • The left subtree of 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.

Stats

Frequency 5
Difficulty 3
Adjusted Difficulty 3
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a textbook-like example of recursion.

I solved it using DFS, but there is actually a much more concise solution.

Code

First, my code, it’s basically a in-order traversal.

int num = Integer.MIN_VALUE;

public boolean isValidBST(TreeNode root) {
    if (root == null) return true;
    if(! isValidBST(root.left)) return false;
    if (num >= root.val) return false;
    num = root.val;
    if(! isValidBST(root.right)) return false;
    return true;
}

Second, great solution I found from this post

public static boolean isValidBST(TreeNode root) {
    return validate(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

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