Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). 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 two trees are mirror images of each other (here: whether a tree is symmetric). 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 mirror(a, b):
    if not a or not b: return a is b
    return a.v == b.v and mirror(a.l, b.r) and mirror(a.r, b.l)
def sym(t): return mirror(t.l, t.r) if t else True
print(sym(build([1, 2, 2, 3, 4, 4, 3])), sym(build([1, 2, 2, None, 3, None, 3])))
What is printed?
  1. A. True True
  2. B. True False
  3. C. False False
  4. D. False True

Correct answer: B. True False

Compare left with right crosswise: outer pair (l.l, r.r) and inner pair (l.r, r.l). In the second tree both 3s are right children, so the shapes are not mirrored even though each level reads [2, 2] and [3, 3] when nulls are ignored. O(n).

More Coding Interview Problems questions

Exams that ask this topic