Katkat

Encode and Rebuild a Binary Tree

AppleData Engineer · Technical Screen

Last 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) -> string
  • decode(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.