Trees and binary search trees · Exercise 30 of 100

Postorder traversal

Traverse the left subtree, traverse the right subtree, then visit their parent. Both children are finished when you visit a node, so you can use their results to calculate something like the size of its subtree.

Try it yourself

Root 9 has left child 4 and right child 12. Node 4 has leaves 2 on the left and 7 on the right. Node 12 has only a right child, the leaf 15. Which value is visited just before 9 in postorder?

One-step hint

Identify the subtree visited last before the root. In postorder, which node closes out that subtree after its leaves?

Worked solution
  1. Finish the left subtree by visiting 2, then 7, then their parent 4.
  2. On the right, visit 15 before its parent 12. Both subtrees are now finished, so 12 is the last visit before 9.
DSA compiler