Data Structures & AlgorithmsEasyWipro · Accenture pattern
What is printed? (level-order traversal of the BST built from these keys)
What is printed? (level-order traversal of the BST built from these keys)
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]]
from collections import deque
r = None
for k in [50, 30, 70, 20, 40, 60, 80, 10]: r = insert(r, k)
q, out = deque([r]), []
while q:
t = q.popleft(); out.append(t[0])
for c in (t[1], t[2]):
if c: q.append(c)
print(out)- A. [10, 20, 30, 40, 50, 60, 70, 80]
- B. [50, 30, 70, 20, 40, 60, 80, 10]
- C. [50, 30, 20, 10, 40, 70, 60, 80]
- D. [50, 70, 30, 80, 60, 40, 20, 10]
Correct answer: B. [50, 30, 70, 20, 40, 60, 80, 10]
Here the insertion order happens to fill the tree level by level, so the level order equals the insertion order. Inorder would be sorted; preorder is 50, 30, 20, 10, 40, 70, 60, 80. BFS with a queue is O(n).
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? (inorder successor in a BST) python def insert(t, k): if t is None: return [k, None, None] i = 1 if k < t[0] else 2 t[i]…
- 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…