Algo-Sim › Binary Trees & BST

Validate Binary Search Tree

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Pass each node the open range (low, high) its ancestors allow. The left child tightens high, the right child tightens low.

Problem

Decide whether a binary tree is a valid binary search tree: for every node, all values in its left subtree are strictly smaller than it and all values in its right subtree are strictly larger, and both subtrees are themselves valid.

Constraints

Edge cases to test

Follow-up questions

Why not just compare each node with its children?
A grandchild can break an ancestor’s bound. Passing (low, high) down, or checking inorder is increasing, catches it.
How do you handle the int limits?
Use null (or long) bounds instead of MIN_VALUE / MAX_VALUE sentinels.

Solution

Java

public boolean isValidBST(TreeNode root) {
    return valid(root, null, null);
}

private boolean valid(TreeNode node, Integer low, Integer high) {
    if (node == null) return true;
    if (low != null && node.val <= low) return false;
    if (high != null && node.val >= high) return false;
    if (!valid(node.left, low, node.val)) return false;
    return valid(node.right, node.val, high);
}

Python

def is_valid_bst(root):
    def valid(node, low, high):
        if not node:
            return True
        if low is not None and node.val <= low:
            return False
        if high is not None and node.val >= high:
            return False
        if not valid(node.left, low, node.val):
            return False
        return valid(node.right, node.val, high)

    return valid(root, None, None)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isValidBST(TreeNode *root) {
        return valid(root, LLONG_MIN, LLONG_MAX);
    }

    bool valid(TreeNode *node, long long low, long long high) {
        if (node == nullptr)
            return true;
        if (node->val <= low)
            return false;
        if (node->val >= high)
            return false;
        if (!valid(node->left, low, node->val))
            return false;
        return valid(node->right, node->val, high);
    }
};

More Binary Trees & BST problems