Round-Trip Text Encoding for Ordered Trees with Any Number of Children
Trees & GraphsModel answerLast 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 (
rootisNone) 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Choosing a format
Each node needs enough information for a decoder to know where its children stop. There are two common options:
- Value plus child count, in preorder. The tree
1 -> (2, 3 -> (4))becomes1 2 2 0 3 1 4 0, read as pairs(val, count):(1,2) (2,0) (3,1) (4,0). - Brackets. The same tree becomes
1(2 3(4)). A(opens a child list and)closes it.
I prefer the count-based format. It is compact and needs no lookahead. Decoding is a direct reading of the structure: read a value, read a count, then decode that many subtrees. Brackets are more readable but require a little more parsing care.
Empty tree: return the empty string "". A single node 7 becomes 7 0. Because every non-empty tree starts with a value and count, the empty string cannot be confused with any real tree.
Negative numbers need no special handling: -5 is just a token, and tokens are split on spaces.
Encoding
Do a preorder traversal and emit val and len(children) for each node. Push children onto an explicit stack in reverse order so they pop in their original order.
def serialize(root):
if root is None:
return ""
out = []
stack = [root]
while stack:
node = stack.pop()
out.append(str(node.val))
out.append(str(len(node.children)))
for child in reversed(node.children):
stack.append(child)
return " ".join(out)
Decoding
Tokens arrive in preorder, so a stack of "nodes still waiting for children" is enough. Each stack entry stores the node and how many children it still needs.
def deserialize(data):
if not data:
return None
tokens = data.split()
if len(tokens) % 2 != 0:
raise ValueError("odd token count")
root = None
stack = [] # entries: [node, remaining_children]
i = 0
while i < len(tokens):
val, cnt = int(tokens[i]), int(tokens[i + 1])
if cnt < 0:
raise ValueError("negative child count")
i += 2
node = Node(val)
if root is None:
root = node
else:
if not stack:
raise ValueError("extra data after root")
parent = stack[-1]
parent[0].children.append(node)
parent[1] -= 1
if cnt > 0:
stack.append([node, cnt])
# pop every ancestor that has received all its children
while stack and stack[-1][1] == 0:
stack.pop()
if stack:
raise ValueError("truncated input")
return root
The order of operations matters: attach the new node to its parent first, then push it if it expects children, then pop all completed ancestors. Popping a finished parent before handling the new node, or forgetting to cascade the pop, are the usual sources of bugs.
Complexity
- Time: O(n) for both directions. Each node is pushed and popped once, and each token is handled once.
- Space: O(n) for the token list and output, plus O(depth) for the stack.
- Build output with a list and a single
join. Repeateds += ...can degrade toward quadratic time.
Deep trees
A recursive encoder or decoder fails on a chain of about 10^5 to 10^6 nodes because of the call-stack limit (roughly 1000 frames by default in Python). The explicit stacks above avoid that. Note that Python's own object destruction of a very deep tree can also be a problem, but that is outside this task.
Malformed input
The decoder above rejects:
- an odd number of tokens,
- non-integer tokens (
int()raises), - negative counts,
- extra tokens after the root is complete,
- truncated input where some node never receives all its children.
If the input is trusted (it always comes from serialize), these checks can be dropped, but they are cheap and worth mentioning. One more defensive point: a huge declared count such as 1 1000000000 does not allocate memory in this design, since children are created only as tokens are read.
Variations and trade-offs
- String values containing delimiters. Spaces and brackets would break the format. Either escape them, or use length-prefixed values such as
5:hello 2, which are unambiguous without escaping. JSON-encoding each value is another safe option. - Compact size. For network or storage use, write varints in a byte buffer, or use base64 of that buffer. Zigzag encoding keeps small negative numbers short.
- Human readability. The bracket format
1(2 3(4))is easier to eyeball and debug, at the cost of slightly more parsing. - Alternative with end markers. Emit
valfollowed by children and a sentinel such as#after each child list. This avoids counts but costs an extra token per node, and the sentinel must not collide with a legal value.
Common mistakes
- Omitting the empty-tree case or mixing it up with a single node.
- Using a sentinel that can equal a real value.
- Pushing children onto the encoding stack in forward order, which reverses sibling order.
- Splitting on commas or spaces while values can contain them.
- Relying on recursion for deep inputs.
- Not cascading pops in the decoder, which leaves finished ancestors on the stack and attaches later nodes to the wrong parent.
Testing
Check these cases: None, a single node, a chain, a star with many leaves, siblings with the same values in different orders, negative and zero values, and a random tree round-tripped through deserialize(serialize(t)) compared structurally. Add a few malformed strings to confirm errors are raised.