297. Serialize and Deserialize Binary Tree

Leetcode

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/arrow-up-right

題目

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary treearrow-up-right. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Example 1:

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []
Output: []

解答

  • 方法一

用 BFS 的方式存 tree nodes

ex.

input => [1,2,3,null,null,4,5,6,7]

serialize => [1,2,3,null,null,4,5,null,null,null,null,6,7,null,null] (把所有空的子節點填 null)

deserialize =>[1,2,3,null,null,4,5,6,7]

但是這種方式如果很多節點都是 null,高度很深的樹的話會有問題,會存放很多不必要的 null 節點

[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9,null,10...] => 像這種樹就會 TLE

Time Limit Exceeded

  • 方法二

使用 DFS 的方法

ex.

input => [1,2,3,null,null,4,5,6,7]

DFS => [1,2,3,4,6,7,5]

serialize => [1,2,null,null,3,4,6,null,null,7,null,null,5,null,null]

arr => [ '1', '2', 'null', 'null', '3', '4', '6', 'null', 'null', '7', 'null', 'null', '5', 'null', 'null', '' ]

deserialize =>[1,2,3,null,null,4,5,6,7]

Runtime: 189 ms, faster than 42.05% of JavaScript online submissions for Serialize and Deserialize Binary Tree.

Memory Usage: 53.9 MB, less than 40.42% of JavaScript online submissions for Serialize and Deserialize Binary Tree.

Last updated