您的位置:首页 > Web前端 > JavaScript

[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};
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: