You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */varserialize=function(root){if(root==null){// 遍历到 null 节点return'X';}constleft=serialize(root.left);// 左子树的序列化结果constright=serialize(root.right);// 右子树的序列化结果returnroot.val+','+left+','+right;// 按 根,左,右 拼接字符串};/** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */vardeserialize=function(data){constlist=data.split(',');constbuildTree=(list)=>{constrootVal=list.shift();if(rootVal==='X'){returnnull}constroot=newTreeNode(rootVal);root.left=buildTree(list);root.right=buildTree(list);returnroot;}returnbuildTree(list);};/** * Your functions will be called as such: * deserialize(serialize(root)); */
The text was updated successfully, but these errors were encountered:
297. 二叉树的序列化与反序列化
Description
Difficulty: 困难
Related Topics: 树, 深度优先搜索, 广度优先搜索, 设计, 字符串, 二叉树
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
示例 1:
示例 2:
示例 3:
示例 4:
提示:
-1000 <= Node.val <= 1000
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: