Encode and Rebuild a Binary Tree
AppleData Engineer · Technical ScreenLast updated
This question evaluates skills in data structure serialization and deserialization, binary tree representation, and algorithmic design for deterministic data formats.
Design two functions for a binary tree:
encode(root) -> stringdecode(data) -> root
Each tree node contains an integer value and has up to two children.
Your encode function should convert a binary tree into a string representation. Your decode function should reconstruct an equivalent binary tree from that string.
Requirements:
- The reconstructed tree must have the same structure and node values as the original tree.
- The format may be any deterministic representation of your choice.
- Empty children must be represented in a way that allows exact reconstruction.
- You may assume node values fit in standard integer range.
Explain the data format you use and implement both functions.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.