Hard Trees

Serialize / Deserialize Binary Tree

Receives an array of integers and builds a binary search tree from them (duplicates ignored), exactly like the Binary Search Tree exercise. It then serializes that tree into a single string by walking it in preorder — the node itself first, then its left subtree, then its right — writing each node's value as a token and a "#" token wherever a child is missing, so the tree's exact shape survives the trip. It parses that same string back into a brand-new tree by consuming the tokens in the same preorder sequence, then reads the rebuilt tree back out in preorder. Returns that final preorder array, which — if serialization and deserialization are correct — is identical to the preorder of the tree that was originally built.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References