00:00

Problem Statement

Input/Output Examples

Visual Explanation

A tree with n nodes has n + 1 empty child positions, so the string always has 2n + 1 tokens, and reading them in order rebuilds each subtree in the same place.

Approaches

Both approaches produce a string that rebuilds the exact tree. One uses preorder recursion; the other uses a queue.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. The two programs use different string formats (preorder and level order), so their serialized strings differ; both rebuild the original tree, which each program checks.

Complexity Analysis

Here n is the number of nodes. Both formats write each node and each empty child once, so they are linear in time and in string length.

Interview Tips and Recommended Approach

  • Record the null children. Values alone cannot distinguish different shapes.
  • Use a separator that cannot appear in values, such as a comma.
  • Test the round trip, including an empty tree and a single node.
  • Know the BST shortcut. A BST can be rebuilt from its preorder alone, without null markers.

Recommended Approach: Preorder With Null Markers

Why: the reader is the exact mirror of the writer, which makes the code short and its correctness easy to argue.