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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The lessons' tree | Not run | |
| 2 | Empty tree | Not run | |
| 3 | One node | Not run | |
| 4 | Wrong child | Not run | |
| 5 | Wrong grandchild | Not run | |
| 6 | Equal keys | Not run | |
| 7 | Too big on the left | Not run | |
| 8 | Negative keys | Not run | |
| 9 | Huge keys | Not run | |
| 10 | 100,000 nodes, correct | Not run | |
| 11 | 100,000 nodes, two keys swapped | Not run |