Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (number of nodes in a complete binary tree in O(log² n))

What is printed? (number of nodes in a complete binary tree in O(log² n))
def count(n_nodes):
    # implicit complete tree with nodes 1..n_nodes (heap numbering)
    def left_h(i):
        h = 0
        while i <= n_nodes: h += 1; i = 2 * i
        return h
    def right_h(i):
        h = 0
        while i <= n_nodes: h += 1; i = 2 * i + 1
        return h
    def go(i):
        if i > n_nodes: return 0
        lh, rh = left_h(i), right_h(i)
        if lh == rh: return (1 << lh) - 1
        return 1 + go(2 * i) + go(2 * i + 1)
    return go(1)
print(count(12), count(15), count(1))
  1. A. 11 15 1
  2. B. 12 16 1
  3. C. 12 15 1
  4. D. 12 15 0

Correct answer: C. 12 15 1

If the leftmost and rightmost depths from a node are equal, its subtree is perfect with 2^h − 1 nodes and needs no further recursion; otherwise recurse. Only one branch per level recurses, giving O(log² n) instead of visiting all n nodes.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic