KatInterview

Tree to String and Back: A Lossless Binary Tree Codec

Trees & GraphsModel answer
HardModel answerTrees & Graphsbinary-treeserializationpreorder

Last 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 by encode back into a binary tree.

Requirements

  • decode(encode(t)) must produce a tree with exactly the same shape and the same node values as t.
  • 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

  1. Describe your format and give the encoding of at least one small example tree.
  2. Implement encode and decode.
  3. Explain why the decoder always recovers the original tree.
  4. 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.