Python coding

Tree to text and back

Design a way to store a binary tree as a string. Write encode(root), which turns the tree into a str, and decode(text), which receives only that string and builds an identical tree: same shape, same values. The format is up to you. Values are integers that can be negative, zero, several digits long or repeated, and the tree may be empty. Write both halves yourself; the provided helpers are only for the tests. Each TreeNode has val, left and right.

The tests call the provided run_round_trip(values), which builds the tree from values (level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3), passes it through encode and then decode, and returns the rebuilt tree in that same format.

  • run_round_trip([1,2,3,null,null,4,5]) → [1,2,3,null,null,4,5]
  • run_round_trip([]) → []
  • run_round_trip([-7,null,120]) → [-7,null,120]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Values alone are not enough: 1,2 could be a left or a right child. Write a marker such as # for every missing child, and a separator between tokens.

Hint 2

With the markers, preorder alone fixes the tree: node, left subtree, right subtree. Decode by reading tokens one at a time in that same order.

Hint 3

Keep one shared position in the token list (an iterator works) instead of slicing it, and compare tokens with "#", not truthiness: the value 0 is a real node.

Solution and why it works
pythonO(n) · O(n) for the text, plus O(h) stack
# --- your code ---
def encode(root: "TreeNode | None") -> str:
    tokens = []
    def walk(node: "TreeNode | None") -> None:
        if node is None:
            tokens.append("#")            # the marker keeps the shape: a leaf is "v,#,#"
            return
        tokens.append(str(node.val))
        walk(node.left)
        walk(node.right)
    walk(root)
    return ",".join(tokens)


def decode(text: str) -> "TreeNode | None":
    tokens = iter(text.split(","))
    def read() -> "TreeNode | None":
        token = next(tokens)
        if token == "#":
            return None
        node = TreeNode(int(token))
        node.left = read()                # same order as encode: node, left, right
        node.right = read()
        return node
    return read()


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def to_values(root: TreeNode | None, limit: int) -> list[int | None]:
    # The inverse of build_tree: level order, None for a missing child, no trailing None.
    out, queue, count = [], [root], 0
    for node in queue:                    # the list grows while we walk it: a BFS queue
        if node is None:
            out.append(None)
            continue
        count += 1
        if count > limit:
            raise ValueError("the result has more nodes than the input: is a node linked twice?")
        out.append(node.val)
        queue += [node.left, node.right]
    while out and out[-1] is None:
        out.pop()
    return out


def run_round_trip(values: list[int | None]) -> list[int | None]:
    text = encode(build_tree(values))
    if not isinstance(text, str):
        raise TypeError(f"encode must return a str, not {type(text).__name__}")
    return to_values(decode(text), sum(v is not None for v in values))

Two different trees can share a preorder, so the walk alone cannot be decoded; marking every missing child removes the ambiguity, and then preorder alone fixes the shape. Decoding replays the same recursion: read a token, stop on #, else make a node and read its left subtree, then its right one. A shared iterator gives each call the next token, O(n) overall. Traps: no separator (12 vs 1,2), dropping the minus sign, and treating the value 0 as a missing node.