Data Structures & AlgorithmsHardAmazon/Microsoft SDE pattern

A binary tree has preorder traversal [72, 40, 18, 19, 54, 47, 92, 81] and inorder traversal [18, 19, 40, 47, 54, 72, 81, 92]. Reconstructing the tree (root = first preorder element, split inorder around it), what is its postorder traversal?

  1. A. 19, 18, 47, 54, 40, 81, 92, 72
  2. B. 18, 19, 40, 47, 54, 72, 81, 92
  3. C. 72, 40, 18, 19, 54, 47, 92, 81
  4. D. 81, 92, 47, 54, 19, 18, 40, 72

Correct answer: A. 19, 18, 47, 54, 40, 81, 92, 72

The first preorder element is the root; its position in the inorder list splits the remaining elements into left and right subtrees, applied recursively. Rebuilding the tree this way and walking it left-right-root gives postorder [19, 18, 47, 54, 40, 81, 92, 72]. Simply reversing the preorder list, [81, 92, 47, 54, 19, 18, 40, 72], only coincidentally matches postorder for some trees, not in general.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic