Trees and binary search trees · Exercise 31 of 100

Check height balance

A binary tree is height-balanced if the heights of the left and right subtrees differ by at most one at every node. Count heights in nodes, giving an empty subtree height zero, and check each pair of child heights as you work up from the leaves.

Try it yourself

Root 10 has left child 6 and right child 14. Node 6 has only a left child, 4, and node 4 has only a left child, 2. Node 14 has only a left child, 12. Is the whole tree height-balanced? Answer yes or no.

One-step hint

Write child heights beside each node, using zero for a missing child. Check the difference at every node on the long left branch as well as at the root.

Worked solution
  1. The root passes its own check because its left subtree has height 3 and its right subtree has height 2.
  2. At node 6, the subtree through 4 has height 2 and the empty right subtree has height 0. The difference is 2, so the answer for the whole tree is no.
DSA compiler