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))
  1. A. 7 3
  2. B. 6 2
  3. C. 6 3
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic