Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Keys are inserted into an empty BST in the order 45, 15, 79, 90, 10, 55, 12, 20, 50. What is the postorder traversal?

Keys are inserted into an empty BST in the order 45, 15, 79, 90, 10, 55, 12, 20, 50. What is the postorder traversal?
def insert(t, k):
    if t is None: return [k, None, None]
    i = 1 if k < t[0] else 2
    t[i] = insert(t[i], k); return t
def pre(t): return [] if t is None else [t[0]] + pre(t[1]) + pre(t[2])
def ino(t): return [] if t is None else ino(t[1]) + [t[0]] + ino(t[2])
def post(t): return [] if t is None else post(t[1]) + post(t[2]) + [t[0]]
r = None
for k in [45, 15, 79, 90, 10, 55, 12, 20, 50]: r = insert(r, k)
print(post(r))
  1. A. [10, 12, 15, 20, 45, 50, 55, 79, 90]
  2. B. [12, 10, 20, 15, 55, 50, 90, 79, 45]
  3. C. [12, 10, 20, 15, 50, 55, 90, 79, 45]
  4. D. [10, 12, 20, 15, 50, 55, 90, 79, 45]

Correct answer: C. [12, 10, 20, 15, 50, 55, 90, 79, 45]

Tree: 45 → left 15 (children 10 → right 12, and 20), right 79 (children 55 → left 50, and 90). Postorder visits left, right, root: 12, 10, 20, 15, 50, 55, 90, 79, 45. The sorted list is the inorder.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic