Encode and Rebuild a Binary Tree
Company: Apple
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates skills in data structure serialization and deserialization, binary tree representation, and algorithmic design for deterministic data formats.
Constraints
- 0 <= number of actual tree nodes <= 10^4
- Each node value is an integer in the standard 32-bit signed range
- The input list uses level-order representation with None for missing children
- The returned level-order list should not contain unnecessary trailing None values
Examples
Input: ([1, 2, 3, None, 4, 5],)
Expected Output: ('1,2,#,4,#,#,3,5,#,#,#', [1, 2, 3, None, 4, 5])
Explanation: Preorder with null markers is 1,2,#,4,#,#,3,5,#,#,#. Decoding that string rebuilds the same tree.
Input: ([],)
Expected Output: ('#', [])
Explanation: An empty tree is encoded as a single null marker '#', and decoding it gives back an empty tree.
Input: ([7],)
Expected Output: ('7,#,#', [7])
Explanation: A single node has value 7 and two null children, so its encoding is 7,#,#.
Input: ([-1, -1, 2, None, -1],)
Expected Output: ('-1,-1,#,-1,#,#,2,#,#', [-1, -1, 2, None, -1])
Explanation: Negative values and duplicates must be preserved exactly in both the serialized form and the rebuilt tree.
Input: ([1, None, 2, None, 3],)
Expected Output: ('1,#,2,#,3,#,#', [1, None, 2, None, 3])
Explanation: This right-skewed tree requires null markers on each missing left child to remain reconstructible.
Hints
- A traversal by itself is not enough to rebuild the exact tree unless you also record missing children.
- While decoding preorder data, think of each node as having two child slots to fill; a stack can help track whether the next token belongs to the left or right side.