Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Insert keys into an empty BST in the given order and report the preorder traversal.
Problem: Insert keys into an empty BST in the given order and report the preorder traversal.
def insert(t, k):
if t is None: return [k, None, None]
if k < t[0]: t[1] = insert(t[1], k)
else: t[2] = insert(t[2], k)
return t
def pre(t): return [] if t is None else [t[0]] + pre(t[1]) + pre(t[2])
root = None
for k in [50, 30, 70, 20, 40, 60, 80, 35]:
root = insert(root, k)
print(pre(root))What is printed?- A. [50, 30, 70, 20, 40, 60, 80, 35]
- B. [20, 30, 35, 40, 50, 60, 70, 80]
- C. [50, 30, 20, 35, 40, 70, 60, 80]
- D. [50, 30, 20, 40, 35, 70, 60, 80]
Correct answer: D. [50, 30, 20, 40, 35, 70, 60, 80]
35 goes left of 50, right of 30, left of 40. Preorder (root, left, right) then reads 50, 30, 20, 40, 35, 70, 60, 80. The insertion order is the level order only for a perfectly filled tree; the sorted list is the inorder. Each insert is O(h).
More Coding Interview Problems questions
- Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder…
- Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity…
- Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level…
- Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are…
- Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix…
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…