Serialize and Deserialize a Binary Tree
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:
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.
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
$99 billed yearly — or $19 month-to-month. Cancel anytime.