⌘K
Flycodx

Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

HardTrees0% accepted

Design an algorithm to serialize (encode to a string) and deserialize (reconstruct from string) a binary tree. The encoding and decoding must be mutually consistent. For this problem: serialize using preorder traversal, using 'null' for absent nodes, values comma-separated. Then deserialize back and print the level-order representation. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: tree [1 2 3 -1 -1 4 5] → serialize → deserialize → output "1 2 3 -1 -1 4 5"

Input format — only if your code reads from stdin

Input format (stdin): - First line: n (level-order array size) - Second line: n space-separated values (-1 for null) — the tree to serialize and deserialize Output: the level-order representation of the reconstructed tree (values space-separated, -1 for null).

Approach

Serialize via preorder DFS: emit node value then recurse left and right. For null nodes, emit 'null'. Deserialize by reading the preorder list recursively: take the next token, if 'null' return null, else create a node and recurse for left and right children.

Input

7 1 2 3 -1 -1 4 5

Output

1 2 3 -1 -1 4 5
  • •0 ≤ n ≤ 1000, -1000 ≤ node values ≤ 1000
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3