Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). 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 bal(t):
    if not t: return 0
    l = bal(t.l)
    if l < 0: return -1
    r = bal(t.r)
    if r < 0 or abs(l - r) > 1: return -1
    return 1 + max(l, r)
print(bal(build([3, 9, 20, None, None, 15, 7])) >= 0, bal(build([1, 2, 2, 3, 3, None, None, 4, 4])) >= 0, bal(build([1, 2, 2, 3, None, None, 3, 4, None, None, None, None, None, None, 4])) >= 0)
What is printed?
  1. A. True False True
  2. B. True True False
  3. C. False False False
  4. D. True False False

Correct answer: D. True False False

Return the height or −1 as an 'unbalanced' flag so each node is visited once (O(n)), instead of calling height() at every node (O(n²) for skewed trees). The second tree has a left subtree of height 3 against a right of height 1. In the third, the root's two subtrees both have height 3, but each node 2 has one child of height 2 and an empty side, so it is unbalanced lower down.

More Coding Interview Problems questions

Exams that ask this topic