← L&T Mindtree bank

L&T Mindtree · Question 57 · Trees

Serialize and Deserialize Binary Tree

TreesJavacode⏱ O(n)💾 O(n)
Service-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:
root = [2, 1, 3]
Output:
2,1,null,null,3,null,null,

Constraints

0 <= nodes <= 10^4.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 5Returns 5source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class CodecDEFINE Stringserialize(TreeNode root)StringBuilder sb = newStringBuilder()build(root, sb)RETURN sb.toString()DEFINE void build(TreeNoder, StringBuilder sb)if (r == null)sb.append("null,")RETURNsb.append(r.val).append(",")build(r.left, sb)build(r.right, sb)DEFINE TreeNodedeserialize(String data)Queue<String> q = newArrayDeque<>(Arrays.asList(data.split(",")))RETURN build(q)DEFINE TreeNodebuild(Queue<String> q)String s = q.poll()if (s.equals("null"))return nullTreeNode node = newTreeNode(Integer.parseInt(s))node.left = build(q)node.right = build(q)RETURN nodeDEFINE TreeNodebuildTree(Integer[] values)if (values.length == 0|| values[0] == null)return nullTreeNode root = newTreeNode(values[0])java.util.Queue<TreeNode> q= newjava.util.LinkedList<>()q.offer(root)DEFINE i = 1while (!q.isEmpty() &&i < values.length)TreeNode node = q.poll()if (i < values.length&& values[i] != null){ node.left = ne…i++if (i < values.length&& values[i] != null){ node.right = ne…i++RETURN rootDEFINE class TreeNodeDEFINE valTreeNode left, rightTreeNode(int v) { val = v;}DEFINE static voidmain(String[] args)Codec codec = new Codec()TreeNode root =buildTree(new Integer[]{2,1, 3})System.out.println(codec.serialize(codec.deserialize(codec.serialize(root))))
  • 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