Data Structures and Algorithms
The values 50, 30, 70, 20, 40, 60, 80 are inserted in this order into an empty binary search tree. In what order are the nodes visited when the tree is traversed in post-order (left subtree, right subtree, then the node)?
- A50, 30, 20, 40, 70, 60, 80
- B20, 40, 30, 60, 80, 70, 50
- C20, 30, 40, 50, 60, 70, 80
Show answer and explanation
Answer: B. 20, 40, 30, 60, 80, 70, 50
The root is 50; its left child is 30 (with children 20 and 40) and its right child is 70 (with children 60 and 80). Post-order visits the left subtree as 20, 40, 30 and the right subtree as 60, 80, 70, and only then the root 50. 50, 30, 20, 40, 70, 60, 80 is the pre-order result, which visits each node first, and 20, 30, 40, … is the in-order result. Post-order is used when children must be processed first, such as when deleting a tree or producing postfix notation from an expression tree.
- A. This is the pre-order result, which visits each node before its subtrees.
- B. Correct. Each node is visited after its left and right subtrees, so the root 50 comes last.
- C. This is the in-order result, which lists the values in ascending order.