TREE-P3

Is it a search tree?

Practice 3 of 6Trees and BSTs11 tests

The problem

Return True if the tree is a binary search tree (lesson 4): for every node, all keys in its left subtree are smaller than its key, and all keys in its right subtree are bigger. Keys must be different, so equal keys mean False.

tree [8, 3, 10, 1, 6, None, 14]   ->  True
tree [5, 1, 4, None, None, 3, 6]  ->  False
tree [5, 4, 6, None, None, 3, 7]  ->  False

In the second tree, 4 is the right child of 5 but smaller than 5. In the third tree, every node is fine next to its own children, but 3 is in the right subtree of 5 and is smaller than 5.

The tests write a tree as a level-order list: the values level by level, left to right, with None where a child is missing. So [3, 9, 20, None, None, 15, 7] is 3 with children 9 and 20, where 20 has children 15 and 7. An empty tree is None.

Limits

  • Up to 100,000 nodes, at most about 50 levels deep. Keys are whole numbers of any size.

Builds on TREE-4 BST search and insert.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1The lessons' treeNot run
2Empty treeNot run
3One nodeNot run
4Wrong childNot run
5Wrong grandchildNot run
6Equal keysNot run
7Too big on the leftNot run
8Negative keysNot run
9Huge keysNot run
10100,000 nodes, correctNot run
11100,000 nodes, two keys swappedNot run