X

DAYS

:

HOUR

:

MINS

:

SEC

Copied to Clipboard
Serialize and Deserialize a Binary Tree
Medium Accuracy: 47.46% Submissions: 39507 Points: 4

Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it.
Note: The structure of the tree must be maintained. Multiple nodes can have the same data.

Example 1:

Input:
1
/   \
2     3
Output: 2 1 3


Example 2:

Input:
10
/    \
20    30
/   \
40  60
Output: 40 20 60 10 30


The task is to complete two function serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
1 <= Number of nodes <= 1000
1 <= Data of a node <= 1000

Note: The Input/Ouput format and Example given above are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code.

We are replacing the old Disqus forum with the new Discussions section given below.