Data Structures & AlgorithmsEasyWipro · Accenture pattern
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 4, 2, 6, 1, 3, 5, 7?
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 4, 2, 6, 1, 3, 5, 7?
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 h(t): return -1 if t is None else 1 + max(h(t[1]), h(t[2]))
r1 = r2 = None
for k in range(1, 8): r1 = insert(r1, k)
for k in [4, 2, 6, 1, 3, 5, 7]: r2 = insert(r2, k)
print(h(r1), h(r2))- A. 7 3
- B. 6 2
- C. 6 3
- D. 3 2
Correct answer: B. 6 2
Sorted insertion builds a right-leaning chain: 7 nodes, 6 edges, so search becomes O(n). Inserting medians first builds a perfect tree of height 2 = ⌊log₂ 7⌋. Self-balancing trees (AVL, red-black) avoid the chain automatically.
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
- 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…
- What is printed? (number of nodes in a complete binary tree in O(log² n)) python def count(nnodes): # implicit complete tree with nodes…