Trees and binary search trees · Exercise 27 of 100
Height of a binary tree
When height counts edges, a leaf has height zero because the path from it to itself uses no links. At a node with children, take the greatest height among its children and add one for the edge to that child.
Try it yourself
Root 9 has children 4 and 12. Node 4 has child 6, node 6 has child 5, and node 5 has child 8. All other child links are empty. What is the height of the tree in edges?
One-step hint
Write zero beside the root and increase the label by one each time you follow a child link. Compare the leaf labels.
Worked solution
- Start at leaf 8 with height 0 and work upward. Node 5 has height 1, node 6 has height 2, and node 4 has height 3.
- At root 9, the taller child is 4 because the other child, 12, is a leaf. Adding the edge from 9 to 4 gives a height of 4.