Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone.
Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone.
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 ser(t):
return '#' if not t else f"{t.v},{ser(t.l)},{ser(t.r)}"
s = ser(build([1, 2, 3, None, None, 4, 5]))
print(s, s.count('#'))What is printed?- A. 1,2,3,#,#,4,5 6
- B. 1,2,#,#,3,4,#,#,5,#,# 6
- C. 1,2,#,#,3,4,#,#,5,#,# 5
- D. 1,2,3,4,5 0
Correct answer: B. 1,2,#,#,3,4,#,#,5,#,# 6
Preorder with null markers is enough to rebuild the tree uniquely. A tree with n nodes has n + 1 null pointers: 5 nodes → 6 '#'. Plain preorder without markers is ambiguous. O(n).
More Coding Interview Problems questions
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…
- 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…
- 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…