BALT-P1

Is it balanced?

Practice 1 of 6Balanced trees9 tests

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

  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.

9 tests, not run yet
Test results
#TestResultReads · time
1BalancedNot run
2Empty treeNot run
3One nodeNot run
4Leaning leftNot run
5Root fine, lower node notNot run
6A path of threeNot run
7Thinnest AVL treeNot run
8Perfect treeNot run
950,000 random keysNot run