VOOZH about

URL: https://www.geeksforgeeks.org/dsa/serialize-deserialize-binary-tree/

⇱ Serialize and Deserialize a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Serialize and Deserialize a Binary Tree

Last Updated : 4 Oct, 2025

Given the root of a binary tree, Complete the functions:

  • serialize(): Traverse the tree, store node values in an array, and insert -1 wherever a node is null. Returns the array representing the tree.
  • deSerialize(): Read the values of the array arr[] to reconstruct the tree. An element arr[i] == -1 represents a missing (null) child.

Note: Multiple nodes can have the same data and the node values are always positive.

[Approach 1] Using Preorder Traversal (Recursive) - O(n) Time and O(n) Space

The idea is to use preorder traversal for serialization. While traversing, if a node is not null, store its value else store -1 as a marker.

  • Serialization: Perform preorder traversal, store node values and insert -1 wherever a node is null.
  • Deserialization: Rebuild the tree by reading values in preorder order. If the value is -1, return null. Otherwise, create a node and recursively build its left and right children.

Pseudo-code Idea (Deserialization)

  • If current value = -1 β†’ return NULL
  • Else Create a new node with the current value
  • Recursively call to build node->left and node->right
  • Return the node

[Approach 2] Using Level Order Traversal - O(n) Time and O(n) Space

The idea is to use level-order traversal for serialization. Push the root into a queue and traverse the tree level by level. For each node, if it exists, store its value and push its left and right children into the queue; if it’s null, store -1 to mark null.
For deserialization, create the root from the first element and push it into a queue. Then, for each element in the array, pop a node from the queue and link its left and right children if the element is -1, the child is null; otherwise, create the node and push it into the queue. This ensures the tree structure is fully preserved.


Comment