Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

A binary tree has preorder traversal [7, 75, 8, 32, 9, 18, 91, 86] and inorder traversal [7, 8, 9, 18, 32, 75, 86, 91]. Reconstructing the tree (root = first preorder element, split inorder around it), what is its postorder traversal?

  1. A. 86, 91, 18, 9, 32, 8, 75, 7
  2. B. 18, 9, 32, 8, 86, 91, 75, 7
  3. C. 7, 75, 8, 32, 9, 18, 91, 86
  4. D. 7, 8, 9, 18, 32, 75, 86, 91

Correct answer: B. 18, 9, 32, 8, 86, 91, 75, 7

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 [18, 9, 32, 8, 86, 91, 75, 7]. Simply reversing the preorder list, [86, 91, 18, 9, 32, 8, 75, 7], only coincidentally matches postorder for some trees, not in general.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic