Trees · Problem 2 of 3

Is this a valid binary search tree?

Pattern: Validate a Binary Search Tree

mediumNot solved yet

The problem

A product catalogue is indexed by price in a binary tree, and it's only fast if the tree is a valid binary search tree. Write a function that returns whether it is: for every node, all values in its left subtree are strictly smaller, and all values in its right subtree are strictly larger. An empty tree counts as valid.

text
1is_search_tree([8, 3, 10, 1, 6, None, 14])  ->  True
2is_search_tree([8, 3, 10, 1, 9])            ->  False
3is_search_tree([5, 5])                      ->  False
Example 2 breaks the rule
8310199 > 8!

9 is in 8's left subtree, so it would need to be smaller than 8.

In the second example, 9 sits in the left subtree of 8 (as 3's right child), but 9 isn't smaller than 8. In the third, equal values aren't allowed.

Write is_search_tree(root) in Python or isSearchTree(root) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 22 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.