Tree to String and Back: A Lossless Binary Tree Codec
Trees & GraphsModel answerLast updated
Build a pair of functions that flatten a binary tree of integers into a string and restore the identical tree from that string, with a clear format and a correctness argument.
You are asked to build a lossless codec for binary trees.
Each node stores an integer and has at most two children (a left and a right child, either of which may be missing).
Implement two functions:
encode(root) -> string: turns a binary tree into a string.decode(text) -> root: turns a string produced byencodeback into a binary tree.
Requirements
decode(encode(t))must produce a tree with exactly the same shape and the same node values ast.- You choose the text format, but it must be deterministic: the same tree always produces the same string.
- Missing children must be recorded so the shape can be recovered exactly. For example, a node with only a left child must be distinguishable from a node with only a right child.
- Node values fit in a standard integer, and may be negative or have several digits.
- The empty tree (
root = None) must round-trip correctly.
What to deliver
- Describe your format and give the encoding of at least one small example tree.
- Implement
encodeanddecode. - Explain why the decoder always recovers the original tree.
- State time and space complexity, and discuss how your solution behaves on very deep (skewed) trees.
Hints
Hint 1
Consider the values 1 and 2 only: a node 1 with one child 2. Does a plain list of visited values tell you whether 2 hangs on the left or the right? What extra information would settle it?
Hint 2
Record a special marker (one that can never look like an integer) for every missing child, and pick a separator so that negative and multi-digit numbers stay unambiguous. With markers in place, a single depth-first, node-before-children traversal is enough.
Hint 3
For decoding, think of the string as a grammar: a tree is either a marker, or a number followed by a tree and then another tree. If you want to avoid recursion limits, keep an explicit stack of nodes whose child slots are not yet filled, and track whether the next slot is left or right.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Why a plain traversal fails
A list of visited values does not fix the shape of a tree. The sequence 1, 2 could be a root with a left child or a root with a right child. The remedy is to write down an explicit marker for every empty child. With those markers, one preorder traversal (node, then left subtree, then right subtree) uniquely identifies the tree.
Format
Tokens are separated by commas:
- an integer token for a real node, such as
-17or42 #for a missing child
Example tree:
1
/ \
2 3
/ \
4 5
Encoding: 1,2,#,#,3,4,#,#,5,#,#
The empty tree encodes to #. A single node 5 encodes to 5,#,#.
The comma handles negative and multi-digit numbers, and # can never be confused with an integer.
Why decoding is unambiguous
Read the format as a grammar:
Tree := "#" | int Tree Tree
Claim: every string the encoder produces parses in exactly one way.
- If the next token is
#, the tree is empty and consumes one token. - Otherwise the token is the root value. The left subtree is the tree that starts immediately after it, and because every empty child is marked, the left subtree ends at a well-defined position (the point where its own grammar is complete). The right subtree is parsed from the tokens that follow.
By induction on the number of nodes, each subtree is reconstructed correctly, so the whole tree is. A useful sanity check: a tree with n nodes has n + 1 empty children, so the string has 2n + 1 tokens.
Iterative approach
The recursive version (read a token, recurse left, recurse right) is the easiest to explain. But a skewed tree with tens of thousands of nodes can exceed the default recursion limit in many languages (about 1000 frames in Python). Mention this and use an explicit stack.
Encode. Push the root. Repeatedly pop an item:
- if it is empty, emit
# - otherwise emit its value, push the right child, then push the left child (so the left is processed first)
Decode. Keep a stack of entries [node, filled] for nodes whose child slots are still open, where filled is 0 (left slot next) or 1 (right slot next). For each token after the root:
- Create the child (a node, or
Nonefor#). - Put it in the top entry's next open slot and increment
filled. - If the top entry now has both slots filled, pop it.
- If the child is a real node, push it, since its children come next in preorder.
Trace on 1,2,#,#,3,#,#: 2 becomes the left child of 1; the next two # fill both slots of 2, which is popped; 3 fills the right slot of 1, which is popped; the last two # fill 3.
Code (Python)
from typing import Optional
class TreeNode:
def __init__(self, val: int = 0,
left: "Optional[TreeNode]" = None,
right: "Optional[TreeNode]" = None):
self.val = val
self.left = left
self.right = right
NULL = "#"
SEP = ","
def encode(root: Optional[TreeNode]) -> str:
tokens = []
stack = [root]
while stack:
node = stack.pop()
if node is None:
tokens.append(NULL)
else:
tokens.append(str(node.val))
stack.append(node.right)
stack.append(node.left)
return SEP.join(tokens)
def decode(data: str) -> Optional[TreeNode]:
tokens = data.split(SEP)
if not tokens or tokens[0] == NULL:
return None
root = TreeNode(int(tokens[0]))
stack = [[root, 0]] # [node, child slots filled]
for tok in tokens[1:]:
child = None if tok == NULL else TreeNode(int(tok))
entry = stack[-1]
parent = entry[0]
if entry[1] == 0:
parent.left = child
else:
parent.right = child
entry[1] += 1
if entry[1] == 2:
stack.pop()
if child is not None:
stack.append([child, 0])
return root
Complexity
- Time: O(n) for both functions. Each node and each marker is handled once, and
joinandsplitare linear. Avoid repeated string concatenation in a loop, which can degrade to quadratic time. - Space: O(n) for the output string or token list. The explicit stack is O(h) for height h, which is O(n) in the worst case, but it lives on the heap rather than the call stack.
Edge cases
- Empty tree:
"#"decodes toNone. - Single node:
"5,#,#". - Negative and multi-digit values: safe thanks to the separator.
- Duplicate values: no issue, because we record structure rather than looking nodes up by value.
- Skewed trees: safe with the iterative version.
- Malformed input: not required, but a robust decoder would raise an error if tokens run out while slots are still open, or if tokens remain after the root's tree is complete.
Trade-offs and alternatives
- Preorder plus inorder can rebuild a tree without markers, but only when all values are distinct, so it is not a general solution.
- Level-order (BFS) with markers is equally valid and naturally iterative. It may emit trailing
#tokens, which can be trimmed to shorten the output. - Compactness: a binary format (for example, a bit per node for presence plus varint values) is smaller than text, at the cost of readability. For a screening problem, the text format is the right default.
Common mistakes
- Omitting null markers and assuming a single traversal suffices.
- Using a separator-free format, so
1followed by2is confused with12, or negative signs are mishandled. - Choosing a null marker that can collide with a valid value.
- Relying on recursion without acknowledging depth limits.
- Building the string with repeated concatenation.
- Offering no argument for correctness beyond one worked example.