progress

~/problems / Trees / Binary trees

Balanced Binary Tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A gardener calls a tree evenly grown when, at every node, the left and right subtrees differ in height by at most one. Height counts nodes on the longest downward path: an empty subtree has height 0, a leaf 1.

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Write is_evenly_grown(root) -> bool. An empty tree (None) is evenly grown.

#        6               6
#       / \             / \
#      2   9           2   9
#     / \             /
#    1   4           1
#                   /
#                  0
is_evenly_grown(left_tree)    # True
is_evenly_grown(right_tree)   # False: at node 6 the left side has height 3, the right side 1
is_evenly_grown(None)         # True

Up to 150,000 nodes; the Python tests stay within 500 levels, so plain recursion is safe. The check must hold at every node, not only the root.

⭐ Bonus: speed tests with 100,000+ nodes earn a star if you find each height once (O(n)).

Show hint

Let one walk hand back two things from each subtree: its height, and whether it's already known to be uneven.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc