FastPrepSerialize and Deserialize a Binary Tree

Serialize and Deserialize a Binary Tree

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Design a way to turn a binary tree into a string and to rebuild the same tree from that string. Use this format:

  • Visit the tree in preorder: the node, then its left subtree, then its right subtree.
  • Write a node as its value, and write an empty child as #.
  • Join all the tokens with one comma, with no spaces.

So the empty tree is #, and one node with value 7 is 7,#,#.

You get two separate inputs, and they may describe different trees. Return an array of two strings:

The problem statement continues
Pro

Examples

Example 1

root = [3,9,100,null,null,48]data = "3,9,#,#,100,48,#,#,#"return = ["3,9,#,#,100,48,#,#,#","[3,9,100,null,null,48]"]

Write 3, then the left subtree: 9,#,#. Then the right subtree: 100, its left child 48,#,#, and its empty right child #. The string data describes the same tree, and in level order it is [3,9,100,null,null,48]. The two null values are the empty children of 9.

FastPrep Pro
Reported in 1 Google interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$8.25/month

$99 billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week
See Google hiring insights
CodePython 3
Run and Submit unlock with Pro
FastPrep Pro
Reported in 1 Google interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$8.25/month

$99 billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week