[LeetCode][JavaScript]Serialize and Deserialize Binary Tree
2015-10-31 18:30
751 查看
Serialize and Deserialize Binary Tree
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.
For example, you may serialize the following tree
1 / \ 2 3 / \ 4 5
as
"[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
串行化和反串行化树。
串行化,中序遍历树,如果left或者right没有孩子,就用N代替,用#连接各个节点。
比图题中的例子,串行化之后是1#2#N#N#3#4#N#N#5#N#N。
反串行化还是中序遍历,递归建出树。
LDR方法有2个返回值,node是当前的节点对象,i是nodes下标。
/** * 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} */ var serialize = function(root) { var res = ""; LDR(root); if(res[0] === '#'){ res = res.substring(1); } return res; function LDR(node){ if(node !== null && node.val !== undefined){ res += "#" + node.val; if(node.left !== null){ LDR(node.left); }else{ res += "#N"; } if(node.right !== null){ LDR(node.right); }else{ res += "#N"; } } } }; /** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */ var deserialize = function(data) { var nodes = data.split('#'); return LDR(0).node; function LDR(i){ if(nodes[i] !== undefined && nodes[i] !== "" && nodes[i] !== 'N'){ var root = new TreeNode(parseInt(nodes[i])); i++; var res = LDR(i); i = res.i; root.left = res.node; res = LDR(i); i = res.i; root.right = res.node; return {node : root, i : i}; }else{ return {node : null, i : ++i}; } } };
相关文章推荐
- 200多个js技巧代码
- 真正的中国天气api接口xml,json(求加精) ...
- JavaScript之模块化编程
- 关于IE浏览器加载外部js注意事项
- [LeetCode][JavaScript]Bulls and Cows
- jsp页面跳转
- 用getAttribute获取控制层获取的数据,显示在jsp页面
- JSON解析与序列化
- JS 乱记
- ExtJS Grid 分页时保持选中的简单实现方法
- javascript制作一个用户登录表单提交检验网页(第一天)
- javascript动态添加div
- JavaScript学习笔记一
- jsp和servlet中实现页面跳转的方式实例总结
- 你不知道的JavaScript--Item25 创建对象(类)的8种方法总结
- 你不知道的JavaScript--Item25 创建对象(类)的8种方法总结
- Json批量数据的存储和访问和输出
- MVC框架之jsp总结
- ECMAScript 6 入门 ----Generator 函数
- 百度地图中热力图使用中json数据转换与构造出现了问题——记录下JSON使用的问题