Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs): # level order, None = missing child
root = T(xs[0]); q = deque([root]); i = 1
while i < len(xs):
node = q.popleft()
for side in ("l", "r"):
if i < len(xs) and xs[i] is not None:
setattr(node, side, T(xs[i])); q.append(getattr(node, side))
i += 1
return root
def invert(t):
if t: t.l, t.r = invert(t.r), invert(t.l)
return t
def inorder(t):
return inorder(t.l) + [t.v] + inorder(t.r) if t else []
print(inorder(invert(build([5, 3, 8, 1, 4, None, 9]))))What is printed?- A. [5, 8, 3, 9, 4, 1]
- B. [9, 8, 5, 4, 3, 1]
- C. [1, 3, 4, 5, 8, 9]
- D. [9, 8, 5, 3, 4, 1]
Correct answer: B. [9, 8, 5, 4, 3, 1]
The original tree is a BST with inorder 1, 3, 4, 5, 8, 9. Mirroring swaps left and right everywhere, so the inorder of the mirror is exactly the original inorder reversed: 9, 8, 5, 4, 3, 1. The tuple assignment evaluates both recursive calls before assigning, so no subtree is lost. O(n).
More Coding Interview Problems questions
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…
- Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a…