Blind 75
35 / 75Free practice

Serialize and Deserialize Binary Tree

Hard · Trees

Jump to code

Create a representation of a binary tree that can reconstruct both its values and exact shape. Support empty trees and negative values.

Examples

Example 1

root = [1,2,3,null,null,4,5]

Output: [1,2,3,null,null,4,5]

Example 2

root = []

Output: []

Constraints

  • 0 <= The number of nodes in the tree <= 1000
  • -1000 <= Node.val <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Implement serialize(root) and deserialize(data). The grader serializes a tree, deserializes that string, and compares the recovered tree. Any unambiguous encoding is accepted.

Need a hint?

Values alone cannot distinguish different shapes.

Real tree interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    3,
    null,
    null,
    4,
    5
  ]
]
Expected
[
  1,
  2,
  3,
  null,
  null,
  4,
  5
]
Case 2
Input
[
  []
]
Expected
[]
Case 3
Input
[
  [
    1
  ]
]
Expected
[
  1
]
Case 4
Input
[
  [
    1,
    2,
    null,
    3
  ]
]
Expected
[
  1,
  2,
  null,
  3
]
Case 5
Input
[
  [
    1,
    null,
    2,
    null,
    3
  ]
]
Expected
[
  1,
  null,
  2,
  null,
  3
]

Drafts are saved per language in this browser when storage is available.