Library Index Audit

Mediumdepth-first searchAlso known as Validate Binary Search Tree

A library's search kiosk finds books with a binary search tree of shelf numbers: at each node it goes left for smaller numbers and right for larger ones, skipping a whole branch each step. That only works if the tree is laid out correctly.

Volunteers edited the tree by hand over the summer. Before the kiosk goes back online, audit it: is every shelf number still where the kiosk will find it?

Your task

Write indexIsValid(root). Return true if the tree is a valid binary search tree, else false. Valid means: for every node, every value in its left subtree is strictly smaller than the node's value, and every value in its right subtree is strictly larger. Equal values anywhere make it invalid.

An empty tree is valid. Trees are shown in level order, like [50, 30, 70, 20, 40], with null for a missing child. Your function receives real TreeNode objects with val, left and right.

indexIsValid(root: TreeNode) → bool

Examples

Example 1
Input
root = [50, 30, 70, 20, 40, 60, 80]
Output
true
Why

Everything under 30 (20, 40) is below 50, everything under 70 (60, 80) is above 50, and each small family is in order. A search for 60 goes right at 50, left at 70, and finds it.

Example 2
Input
root = [50, 30, 70, 20, 55, 60, 80]
Output
false
Why

55 is the right child of 30, and 55 > 30, so that pair looks fine. But 55 is in 50's left subtree, where every number must be below 50. A search for 55 would go right at 50 and never find it.

Constraints

  • 0 ≤ number of shelf numbers ≤ 1,000
  • -2,147,483,648 ≤ shelf number ≤ 2,147,483,647
  • The tree is at most 500 levels deep.
Start with brute force

For each node, scan its whole left subtree to confirm everything is smaller, and its right subtree to confirm everything is larger.

A node near the top scans almost the whole tree; a chain of 1,000 nodes costs about 500,000 comparisons, O(n²). Deep nodes get rechecked against every ancestor separately. Carrying the tightest limits down checks each node once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code