The problem
A binary tree is height-balanced if at every node the heights of its left and right subtrees differ by at most 1. This is the AVL rule from lesson 3. An empty subtree has height −1. Return True if the tree is height-balanced and False if not.
tree [3, 9, 20, None, None, 15, 7] -> True
tree [1, 2, 2, 3, 3, None, None, 4, 4] -> False
empty tree -> True
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.
The values are not sorted: this can be any binary tree.
Limits
- Up to 131,071 nodes, at most 300 levels deep, so recursion is fine.
- Your solution should take O(n) time: work out each height once.
Builds on BALT-1 Why balance matters and BALT-3 AVL trees.
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 | Balanced | Not run | |
| 2 | Empty tree | Not run | |
| 3 | One node | Not run | |
| 4 | Leaning left | Not run | |
| 5 | Root fine, lower node not | Not run | |
| 6 | A path of three | Not run | |
| 7 | Thinnest AVL tree | Not run | |
| 8 | Perfect tree | Not run | |
| 9 | 50,000 random keys | Not run |