← Meta (Facebook) bank

Meta (Facebook) · Question 57 · Trees

Serialize and Deserialize Binary Tree

TreesPythoncode⏱ O(n)💾 O(n)
Product-based

Problem

You are required to design algorithm to serialize and deserialize binary tree.

Approach

Preorder with 'null' markers serializes; recursive consumption rebuilds.

Time O(n)Space O(n)

How it works

  1. 1Emit values preorder with 'null' for missing children.
  2. 2Rebuild by consuming tokens in the same order.

Sample input / output

Input:
7
1 2 3 x x 4 5
Output:
1,2,null,null,3,4,null,null,5,null,null,

Constraints

0 <= nodes <= 10^4; -1000 <= Node.val <= 1000.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 5Returns 7source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesno↻ repeatSTARTCLASS CodecDEFINE serialize(self,root)if not rootRETURN "null,"RETURN str(root.val) + ","+ self.serialize(root.left)…DEFINE deserialize(self,data)DEFINE helper(data_list)val = data_list.pop(0)if val == "null"RETURN Noneroot = TreeNode(int(val))root.left =helper(data_list)root.right =helper(data_list)RETURN rootdata_list = data.split(',')RETURN helper(data_list)CLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE build_tree(values)if not valuesRETURN Noneroot = TreeNode(values[0])queue = [root]i = 1while queue and i <len(values)node = queue.pop(0)if i < len(values) andvalues[i] is not Nonenode.left =TreeNode(values[i])queue.append(node.left)i += 1if i < len(values) andvalues[i] is not Nonenode.right =TreeNode(values[i])queue.append(node.right)i += 1RETURN rootDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))vals = [None if t == 'x'else int(t) for t in[next(it) for _ i…root = build_tree(vals)
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits