Practice Real Company Assessment Patterns • Latest 2025–2026 Mock Tests

Programming Exercises

Write a function that serializes and deserializes a binary tree.

Hard

Problem Statement

Write a function that serializes and deserializes a binary tree.

Sample Input

A binary tree to serialize and then deserialize.

Sample Output

{ val: 1,
  left: { val: 2, left: null, right: null },
  right: 
   { val: 3,
     left: { val: 4, left: null, right: null },
     right: { val: 5, left: null, right: null } } }

Limits

Time: 2s · Memory: 256 MB

Code Editor
00:00
// Serialize and deserialize a binary tree function serialize(root) { // Convert tree nodes to a string representation } function deserialize(data) { // Convert string back to tree nodes } // Example usage const root = { val: 1, left: { val: 2 }, right: { val: 3, left: { val: 4 }, right: { val: 5 } } }; console.log(deserialize(serialize(root)));
Log in or sign up to run or submit your code.Log inSign up
Input
A binary tree to serialize and then deserialize.
Expected Output
{ val: 1,
  left: { val: 2, left: null, right: null },
  right: 
   { val: 3,
     left: { val: 4, left: null, right: null },
     right: { val: 5, left: null, right: null } } }