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?- A. True False True
- B. True True False
- C. False False False
- 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
- Problem: Return the zigzag level order (left→right, then right→left, alternating). Trees are built by build(xs): a level-order list where…
- Problem: Convert a sorted array into a height-balanced BST and print its preorder. python def pre(a, lo, hi, out): if lo > hi: return out…
- Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing…
- Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height…
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…
- Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built…