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?- A. True True
- B. True False
- C. False False
- 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
- 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…
- Problem: Find the minimum depth (nodes on the shortest root-to-LEAF path). The candidate below is buggy. Trees are built by build(xs): a…
- Problem: Insert keys into an empty BST in the given order and report the preorder traversal. python def insert(t, k): if t is None: return…
- Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder…
- Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity…
- Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level…