Skip to content
BytePatterns

Compact BST Serialization

MediumTrees & BST#preorder#monotonic-stack#bst~30m

Problem

Write encode(root), which turns a binary search tree with distinct whole-number keys into a string, and decode(text), which rebuilds the exact same tree. The string may contain only the keys separated by single spaces, with no markers for missing children, so it is as short as the keys allow. Both functions should run in linear time and should not recurse, because the tree can be as tall as it has nodes.

Examples

Input:  tree = 8, left 3 (children 1 and 6), right 10 (right child 14)
Output: encode -> "8 3 1 6 10 14"
        decode("8 3 1 6 10 14") rebuilds the same shape
Why:    pre-order lists each node before its children
Input:  tree = a chain 1 -> 2 -> 3, each key the right child of the previous one
Output: encode -> "1 2 3"
Why:    decode knows 2 cannot be a left child of 1, since 2 is larger
Input:  tree = empty
Output: encode -> ""
        decode("") -> empty tree
Why:    edge case, nothing to write

Hints

0 / 3

Stuck on the idea rather than the code? Serialize a Tree covers it.