Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def h(t):
    return 0 if not t else 1 + max(h(t.l), h(t.r))
print(h(build([1, 2, 3, None, 5, None, None, None, None, 8])))
What is printed?
  1. A. 3
  2. B. 5
  3. C. 2
  4. D. 4

Correct answer: D. 4

Post-order: a node's height is 1 + the larger child height. The path 1 → 2 → 5 → 8 has 4 nodes (index 9 is the left child of index 4). Counting edges instead of nodes gives 3. O(n) time, O(h) stack.

More Coding Interview Problems questions

Exams that ask this topic