Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What is printed? (inorder successor in a BST)
What is printed? (inorder successor in a BST)
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]]
def succ(t, k):
best = None
while t:
if k < t[0]: best, t = t[0], t[1]
else: t = t[2]
return best
r = None
for k in [20, 8, 22, 4, 12, 10, 14]: r = insert(r, k)
print(succ(r, 8), succ(r, 14), succ(r, 22))- A. 12 20 None
- B. 10 22 None
- C. 10 20 None
- D. 10 20 22
Correct answer: C. 10 20 None
Walk from the root: whenever k is smaller than the node, that node is a candidate and we go left; otherwise go right. 8's successor is the leftmost node of its right subtree (10); 14 has no right subtree, so its successor is the nearest ancestor where we went left (20); 22 is the maximum → None. O(h).
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
- What is printed? (heap sort on a small array, showing the array after the first extraction) python def sift(a, i, n): while 2 i + 1 < n: c…
- What is printed? (trie: count distinct prefixes / nodes) python words = ["tea", "ten", "to", "inn", "in", "i"] root, nodes = {}, 0 for w…
- What is printed? (count connected components with DFS on an adjacency list) python n = 8 edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7)…
- Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1? python INF = float('inf') d = [[0, 3, INF, 7]…
- Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)? python edges = [(0, 1…
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…