Video in progress

This code tries to check whether a binary tree is a BST. What is wrong?

static boolean isBst(TreeNode n) {
    if (n == null) return true;
    if (n.left() != null && n.left().val() >= n.val()) return false;
    if (n.right() != null && n.right().val() <= n.val()) return false;
    return isBst(n.left()) && isBst(n.right());
}

The code compares a node only with its own children. But the BST rule requires the entire left subtree to be smaller than the node and the entire right subtree to be larger. The right way is to pass the allowed (min, max) range down to each node.

📖 Answer

This tree passes the check, but it is not a BST:

      10
     /  \
    5    15
        /  \
       6    20

6 is smaller than its own parent 15, so the local condition holds. But it sits on the right side of 10, so it had to be larger than 10.

The corrected version passes the bounds down:

static boolean isBst(TreeNode n, long min, long max) {
    if (n == null) return true;
    if (n.val() <= min || n.val() >= max) return false;
    return isBst(n.left(), min, n.val())
        && isBst(n.right(), n.val(), max);
}
// call: isBst(root, Long.MIN_VALUE, Long.MAX_VALUE)

Why long? If a node holds Integer.MAX_VALUE, you'd wrongly reject it with int bounds. The other way is to make the bounds Integer and treat null as "no bound".

An alternative approach: do an inorder traversal and check that each value is strictly greater than the previous one. Both are O(n).