CodingNodes / Trees / Validate Binary Search Tree System design Space play · ←→ step · R restart

Problem

A binary search tree keeps every value in a node's left subtree strictly smaller than the node, and every value in its right subtree strictly larger, all the way down.

Given the root of a binary tree, return true if it is a valid search tree and false otherwise. The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 10000
  • -2^31 ≤ Node.val ≤ 2^31 - 1

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is checked once, with constant work per node.

Space: The recursion is as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

Every node has a range its value must fall in: strictly above lo and strictly below hi. The root may be anything. Going left, the node's value becomes the new hi; going right, it becomes the new lo. A node outside its range makes the whole tree invalid. The bounds are stored as wider numbers than the node values, so a node equal to the biggest or smallest int still fits.