Valid Binary Search Tree

Problem

Given the root of a binary tree, return true if it is a valid binary search tree, otherwise return false.

valid binary search tree satisfies the following constraints:

  • The left subtree of every node contains only nodes with keys less than the node’s key.
  • The right subtree of every node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees are also binary search trees.

Examples

Example 1:

Input: root = [2,1,3]

Output: true

Example 2:

Input: root = [1,2,3]

Output: false

Constraints

  • 1 <= The number of nodes in the tree <= 1000.
  • -1000 <= Node.val <= 1000

You should aim for a solution with O(n) time and O(n) space, where n is the number of nodes in the given tree.

Solution

We keep a window of the valid values each node can have in the subtrees, like alpha-beta search. Start with an infinite range.

  • The left subtree’s window is
  • The right subtree’s window is
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        // Keep a window of available values that the node must fall within
        // Think like alpha beta search
        std::function<bool(TreeNode*, int, int)> runner;
        runner = [&](TreeNode *node, int min_val, int max_val) -> bool {
            if (!node) { return true; }
            if (!(node->val > min_val && node->val < max_val)) {
                return false;
            }
            return runner(node->left, min_val, node->val) && runner(node->right, node->val, max_val);
        };
        return runner(root, std::numeric_limits<int>::lowest(), std::numeric_limits<int>::max());
    }
};