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?
  1. A. 1,2,3,#,#,4,5 6
  2. B. 1,2,#,#,3,4,#,#,5,#,# 6
  3. C. 1,2,#,#,3,4,#,#,5,#,# 5
  4. 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

Exams that ask this topic