KatInterview

Round-Trip Text Encoding for Ordered Trees with Any Number of Children

Trees & GraphsModel answer
MediumModel answerTrees & Graphstreeserializationn-ary-tree

Last updated

Define a text format for ordered trees with arbitrary branching, then write an encoder and decoder that rebuild the exact same values, structure and child order in linear time.

You are given ordered trees in which every node holds an integer and can have any number of children, arranged in a fixed left-to-right order. Invent a text format for these trees and implement the two conversions:

  • serialize(root) returns a string describing the tree.
  • deserialize(data) takes that string and returns the tree.

Decoding the output of encoding must give back the original tree exactly: identical values, identical shape, and identical child order at every node. deserialize may only use the string it receives; nothing can be remembered between calls.

class Node:
    def __init__(self, val, children=None):
        self.val = val
        self.children = children if children is not None else []

def serialize(root: Node | None) -> str: ...
def deserialize(data: str) -> Node | None: ...

Rules and assumptions

  • Values are integers and may be negative.
  • The tree can be empty (root is None) or a single node.
  • Child order matters. Two trees that differ only in the order of one node's children are different trees.

What to discuss

  • How your format tells a decoder where each node's children begin and end.
  • Time and space complexity. Avoid quadratic string building.
  • How you would cope with very deep trees (for example, a chain of a million nodes).
  • What your decoder does with truncated or malformed input.
  • What would change if values were arbitrary strings that might contain your delimiter characters, or if the encoded size mattered.

Hints

Hint 1

A decoder needs to know, for each node, either how many children follow or where the child list ends. Pick one of those and make sure the format always supplies it.

Hint 2

Try a preorder walk that writes the value followed by the child count. Reading it back is then a recursive rule: read value, read count, decode that many subtrees. Represent the empty tree with a special marker or an empty string.

Hint 3

Recursion depth equals tree depth, which can overflow the call stack. Replace both the encoder and the decoder with an explicit stack, and build the output as a list of tokens joined once at the end.