Data Structures & AlgorithmsHardHCLTech · Wipro pattern

A binary tree has preorder traversal [9, 97, 20, 59, 28, 78] and inorder traversal [9, 20, 28, 59, 78, 97]. Reconstructing the tree (root = first preorder element, split inorder around it), what is its postorder traversal?

  1. A. 9, 20, 28, 59, 78, 97
  2. B. 28, 78, 59, 20, 97, 9
  3. C. 9, 97, 20, 59, 28, 78
  4. D. 78, 28, 59, 20, 97, 9

Correct answer: B. 28, 78, 59, 20, 97, 9

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 [28, 78, 59, 20, 97, 9]. Simply reversing the preorder list, [78, 28, 59, 20, 97, 9], only coincidentally matches postorder for some trees, not in general.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic