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))- A. [10, 12, 15, 20, 45, 50, 55, 79, 90]
- B. [12, 10, 20, 15, 55, 50, 90, 79, 45]
- C. [12, 10, 20, 15, 50, 55, 90, 79, 45]
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- For the same kind of BST, what is the height (edges on the longest root-to-leaf path) after inserting 1, 2, 3, 4, 5, 6, 7 in order, versus…
- A max-heap is built with heapify on the array below (0-based, children 2i+1 and 2i+2). What is the resulting array? python def sift(a, i…
- From the max-heap [50, 30, 40, 10, 20, 35, 25], delete the maximum once. What is the array? python import heapq h = [-x for x in [50, 30…
- What is printed? (count leaves, internal nodes and full nodes of a binary tree) python T = {1: (2, 3), 2: (4, None), 3: (5, 6), 4: (None…
- A binary tree has preorder A B D E C F G and inorder D B E A F C G. What is its postorder? python def post(pre, ino): if not pre: return…
- How many structurally different binary trees have n = 4 nodes, and how many distinct labelled binary trees can be formed from 4 distinct…