跳至主要內容

297. Serialize and Deserialize Binary Tree


297. Serialize and Deserialize Binary Treeopen in new window

🔴   🔖  深度优先搜索 广度优先搜索 设计 字符串 二叉树  🔗 LeetCodeopen in new window

题目

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 treeopen in new window. 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: []

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000

题目大意

设计一个算法,来序列化和反序列化二叉树。并不限制如何进行序列化和反序列化,但是你需要保证二叉树可以序列化为字符串,并且这个字符串可以被反序列化成原有的二叉树。

解题思路

  1. 序列化其实就是二叉树的遍历,顺手把遍历的结果转化成字符串的形式;
  2. 反序列化就是二叉树的还原,把序列化字符串还原成二叉树;
  3. 以前序遍历为例,前序遍历的特点是根节点在开头,然后是左子树的前序遍历结果,然后是右子树的前序遍历结果;
  4. 序列化时,不存在的结点用 null 填充,左右子树之间用 ',' 分割;
  5. 反序列化过程中,首先将序列化字符串按逗号进行切分,得到一个节点值的列表。然后,通过递归地从这个列表中取值,构建二叉树。反序列化的过程中,每次取第一个值即为当前节点的值,然后递归构建左子树和右子树。

代码

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  if (!root) return "null";
  let left = serialize(root.left);
  let right = serialize(root.right);
  return root.val + "," + left + "," + right;
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function (data) {
  const buildTree = (nodes) => {
    const val = nodes.shift();
    if (val == "null") return null;
    let root = new TreeNode(val);
    root.left = buildTree(nodes);
    root.right = buildTree(nodes);
    return root;
  };

  const nodes = data.split(",");
  return buildTree(nodes);
};

相关题目

相关题目
- [🔒 Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings)
- [449. 序列化和反序列化二叉搜索树](https://leetcode.com/problems/serialize-and-deserialize-bst)
- [652. 寻找重复的子树](https://leetcode.com/problems/find-duplicate-subtrees)
- [🔒 Serialize and Deserialize N-ary Tree](https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree)