![]() |
VOOZH | about |
Given the root of a binary tree, Complete the functions:
Note: Multiple nodes can have the same data and the node values are always positive.
Table of Content
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.
Pseudo-code Idea (Deserialization)
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.