...

/

Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

Try to solve the Serialize and Deserialize Binary Tree problem.

Statement

Serialize a given binary tree to a file and deserialize it back to a tree. Make sure that the original and the deserialized trees are identical.

  • Serialize: Write the tree to a file.

  • Deserialize: Read from a file and reconstruct the tree in memory.

Serialize the tree into an array of integers, and then, deserialize it back from the array to a tree. For simplicity’s sake, there’s no need to write the array to the files.

Constraints:

  • The number of nodes in the tree is in the range [0,500][0, 500].
  • 1000-1000 \leq Node.value 1000\leq 1000

Examples

canvasAnimation-image
1 / 2

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Serialize and Deserialize Binary Tree

1.

What is the serialized output of this tree using level order traversal?

          __ 350 
	     |
	  __ 75 ______ 
	 |            |
	 25 _     ___ 200 
	     |   |
	     50  100
A.

[350, 75, 25, 50, 200, 100]

B.

[350, 75, 25, 200, 50, 100]

C.

[25, 50, 75, 100, 200, 350]

D.

[50, 25, 100, 200, 75, 350]


1 / 2

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to re-arrange them in the correct sequence

1
2
3
4

Try it yourself

Implement your solution in main.go in the following coding playground.

Go
usercode > main.go
// Definition of a binary tree node
// type TreeNode[T any] struct {
// Data T
// Left *TreeNode[T]
// Right *TreeNode[T]
// }
package main
import (. "golang-test-code/ds_v1/BinaryTree") // TreeNode[T]
func serialize(root *TreeNode[int]) []string {
// Replace this placeholder return statement with your code
return make([]string, 0)
}
func deserialize (stream *[]string) *TreeNode[int] {
// Replace this placeholder return statement with your code
return nil
}
Serialize and Deserialize Binary Tree

Access this course and 1200+ top-rated courses and projects.