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 shelf number the kiosk goes left to look for smaller numbers and right to look for larger ones, so it can skip a whole branch at every step. That only works if the tree is laid out correctly.

Over the summer, volunteers edited the tree by hand. Before the kiosk goes back online, the head librarian wants an audit: is every shelf number still in a place where the kiosk will find it?

Your task

Write indexIsValid(root). Return true if the tree is a valid binary search tree, and false otherwise. In a valid tree, 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], where null marks 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 and 40) is below 50, everything under 70 (60 and 80) is above 50, and each small family is in order too. 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 sits in the left subtree of 50, 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 entire left subtree to confirm everything is smaller, and its entire right subtree to confirm everything is larger.

That is correct, but a node near the top scans almost the whole tree, and a long chain of 1,000 nodes makes it about 500,000 comparisons, which is O(n²). The repeated work is checking the same deep nodes against every ancestor separately. Carrying the tightest limits down the tree 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