序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
示例 1:
输入:root = [1,2,3,null,null,4,5] 输出:[1,2,3,null,null,4,5]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[1,2]
提示:
- 树中结点数在范围
[0, 104]
内 -1000 <= Node.val <= 1000
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 9 /** 10 * Encodes a tree to a single string. 11 * 12 * @param {TreeNode} root 13 * @return {string} 14 */ 15 var serialize = function(root) { 16 return rserialize(root, ''); 17 }; 18 19 /** 20 * Decodes your encoded data to tree. 21 * 22 * @param {string} data 23 * @return {TreeNode} 24 */ 25 var deserialize = function(data) { 26 const dataArray = data.split(","); 27 return rdeserialize(dataArray); 28 }; 29 30 /** 31 * Your functions will be called as such: 32 * deserialize(serialize(root)); 33 */ 34 const rserialize = (root, str) => { 35 if (root === null) { 36 str += "None,"; 37 } else { 38 str += root.val + '' + ","; 39 str = rserialize(root.left, str); 40 str = rserialize(root.right, str); 41 } 42 return str; 43 } 44 45 const rdeserialize = (dataList) => { 46 if (dataList[0] === "None") { 47 dataList.shift(); 48 return null; 49 } 50 51 const root = new TreeNode(parseInt(dataList[0])); 52 dataList.shift(); 53 root.left = rdeserialize(dataList); 54 root.right = rdeserialize(dataList); 55 56 return root; 57 }标签:null,return,dataList,二叉树,str,297,序列化,root From: https://www.cnblogs.com/icyyyy/p/16864516.html