← Whiteboard questions

Serialize and Deserialize Binary Tree

Turn a tree into text and read it back

DSA, Hard, Trees

Which structure or algorithm, and what does it cost.

Write two functions. encode(root) takes the root of a binary tree (each node has val, left and right, null when missing) and returns a string. decode(text) returns the root of the same tree. Taking and returning the level-order list instead is also fine. The examples write trees as level-order lists: values row by row, with null for a missing child. For every tree, decode(encode(tree)) must give back the same tree. The text format is yours, but it may use at most 15 characters for each node, plus 15.

Examples

Input tree = [5, 3, 8, null, 4, 7]
Output [5, 3, 8, null, 4, 7]
Why decode gives back the same tree. One valid text is 5,3,#,4,#,#,8,7,#,#,#.
Input tree = []
Output []
Why an empty tree needs a text too. One valid text is #.
Input tree = [-2, null, -9, 3]
Output [-2, null, -9, 3]
Why negative values must survive. One valid text is -2,#,-9,3,#,#,#.

Constraints

Your answer must contain

Target Aim for O(n) time for each function.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

The text must hold enough to rebuild the tree. What would two different trees with the same values have in common if you wrote only the values?

Hint 2 the approach

The text must also record where children are missing. Choose a marker that no value can equal, and one fixed order to write the nodes.

Hint 3 the key step

Write nodes in preorder: the value, or a marker for a missing child. To decode, read the pieces in order and fill the open child slots, the left slot first.

Walkthrough

Full walkthrough brute force to best

Brute force

Write the tree as a full grid: one slot for every position down to the deepest level, with a marker in each empty slot. A tree of height h needs 2^h - 1 slots. A chain of 40 nodes would need over a trillion slots, so this is O(2^h) time and memory.

Best method

Write the nodes in preorder: the node value, then its whole left side, then its whole right side. Write a marker for every missing child. With the markers, the text says exactly where each branch ends, so only one tree fits it. Separate the pieces with commas, so values of different lengths and negative signs cannot blur together. To read it back, take the pieces in order and keep a stack of child slots that are still empty. Each piece fills the most recent open slot. A value makes a node and opens two new slots, with the left one on top. A marker fills the slot with nothing. Each piece is handled once, so both functions are linear. The stack keeps a long chain from overflowing the call stack.

Hand trace

Encode [5, 3, 8, null, 4, 7]. The tree: 5 has children 3 and 8. Node 3 has a right child 4. Node 8 has a left child 7. Preorder from 5: write 5, go left to 3, write 3, its left is missing so write #, go right to 4, write 4, then # and # for its missing children. Back at 5, go right to 8, write 8, go left to 7, write 7, then # and # for its missing children, then # for the missing right child of 8. The text is 5,3,#,4,#,#,8,7,#,#,#. Decode: 5 makes the root with two open slots. 3 fills its left slot. # fills the left slot of 3. 4 fills the right slot of 3. Two # fill the slots of 4. 8 fills the right slot of 5. 7 fills the left slot of 8. Three # close the rest. The result is [5, 3, 8, null, 4, 7].

Code

class Node:
    def __init__(self, val):
        self.val = val
        self.left = self.right = None
def encode(root):
    out, stack = [], [root]
    while stack:
        node = stack.pop()
        if node is None:
            out.append('#')
            continue
        out.append(str(node.val))
        stack.append(node.right)
        stack.append(node.left)
    return ','.join(out)
def decode(text):
    tokens = text.split(',')
    if tokens[0] == '#':
        return None
    root = Node(int(tokens[0]))
    slots = [(root, 'right'), (root, 'left')]
    for token in tokens[1:]:
        parent, side = slots.pop()
        if token != '#':
            child = Node(int(token))
            setattr(parent, side, child)
            slots.extend([(child, 'right'), (child, 'left')])
    return root

Time and memory

O(n) time for each function, because each node and each marker is written or read once. O(n) memory for the text, and O(h) extra for the stack, where h is the height.

Common mistakes

  • Writing only the values. Different trees can have the same values, so the text cannot be decoded without the markers.
  • Using a number such as -1 or 0 as the marker. Values can be negative or zero, so use a symbol that no value can equal.
  • Leaving out the separator. Without commas, 12 and 1, 2 look the same.

Related problems

More Trees problems
Serialize and Deserialize Binary Tree walkthrough