Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.

For example, given the following Node class

class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right

The following test should pass:

node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'

Define createNode function:

function createNode(val, left = null, right = null) {
return {
val,
left,
addLeft(leftKey) {
return this.left = leftKey ? createNode(leftKey) : null;
},
right,
addRight(rightKey) {
return this.right = rightKey ? createNode(rightKey) : null;
}
};
}

Define a binary tree:

function createBT(rootKey) {
const root = createNode(rootKey);
return {
root,
nodes: [],
serialize(node) { },
deserialize(str) { }
};
}

Construct the tree:

const tree = createBT("root");
const root = tree.root;
const left = root.addLeft("left");
root.addRight("right");
left.addLeft("left.left");
left.addRight("left.right");

Serialize the tree:

The idea to serialize a tree is using recsurice apporach, keep calling serialize function for the left side node, then keep calling serialize function for right side nodes.

In the end, we output the serialized nodes in string format.

    serialize(node) {
if (node) {
this.nodes.push(node.val);
this.serialize(node.left);
this.serialize(node.right);
} else {
this.nodes.push("#");
}
return this.nodes.join(" ");
},
const ser = tree.serialize(root); // root left left.left # # # right # #

Deserialize tree:

By given the serialized tree, every time we calling recsurice, we are trying to create Node, then append its left and right node.

    deserialize(str) {

      function* getVals() {
for (let val of str.split(" ")) {
yield val;
}
} const helper = (pointer) => {
let { value , done } = pointer.next();
if (value === "#" || done) return null; let node = createNode(value);
node.left = helper(pointer);
node.right = helper(pointer);
return node;
};
return helper(getVals());
}
const dec = tree.deserialize(ser).left.left.val; // left.left

-----

function createNode(val, left = null, right = null) {
return {
val,
left,
addLeft(leftKey) {
return this.left = leftKey ? createNode(leftKey) : null;
},
right,
addRight(rightKey) {
return this.right = rightKey ? createNode(rightKey) : null;
}
};
} function createBT(rootKey) {
const root = createNode(rootKey);
return {
root,
nodes: [],
serialize(node) {
if (node) {
this.nodes.push(node.val);
this.serialize(node.left);
this.serialize(node.right);
} else {
this.nodes.push("#");
}
return this.nodes.join(" ");
},
deserialize(str) { function* getVals() {
for (let val of str.split(" ")) {
yield val;
}
} const helper = (pointer) => {
let { value , done } = pointer.next();
if (value === "#" || done) return null; let node = createNode(value);
node.left = helper(pointer);
node.right = helper(pointer);
return node;
};
return helper(getVals());
}
};
}
////////Construct the tree///////////
const tree = createBT("root");
const root = tree.root;
const left = root.addLeft("left");
root.addRight("right");
left.addLeft("left.left");
left.addRight("left.right"); ///////////Serialize and deserialize//////////////
const ser = tree.serialize(root); // root left left.left # # # right # #
const dec = tree.deserialize(ser).left.left.val; // left.left
console.log(ser, dec)

[Algorithm] Serialize and Deserialize Binary Tree的更多相关文章

  1. [LeetCode] Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...

  2. LC 297 Serialize and Deserialize Binary Tree

    问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...

  3. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  4. [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)

    描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...

  5. [Algorithm] 7. Serialize and Deserialize Binary Tree

    Description Design an algorithm and write code to serialize and deserialize a binary tree. Writing t ...

  6. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  7. LeetCode——Serialize and Deserialize Binary Tree

    Description: Serialization is the process of converting a data structure or object into a sequence o ...

  8. Serialize and Deserialize Binary Tree

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  9. 297. Serialize and Deserialize Binary Tree

    题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...

随机推荐

  1. 【10.26校内测试】【状压?DP】【最小生成树?搜索?】

    Solution 据说正解DP30行??? 然后写了100行的状压DP?? 疯狂特判,一算极限时间复杂度过不了aaa!! 然而还是过了....QAQ 所以我定的状态是待转移的位置的前三位,用6位二进制 ...

  2. bzoj hash+map+set

    先对原串分组hash,查询就是看某一区间内是否出现某值. 可以每个值存一个集合,保存这个值出现的位置.(也可以建可持久化值域线段树) map<int,set<int> >很省事 ...

  3. Codeforces Round #360 (Div. 2) B. Lovely Palindromes 水题

    B. Lovely Palindromes 题目连接: http://www.codeforces.com/contest/688/problem/B Description Pari has a f ...

  4. euclidea 3.0 全三星 攻略

    euclidea攻略 游戏地址 http://www.euclidea.xyz/en/game/#/packs 攻略 Alpha level : 1.1 line tool 3L3E 智障题 1.2 ...

  5. Codeforces Beta Round #97 (Div. 1) B. Rectangle and Square 暴力

    B. Rectangle and Square 题目连接: http://codeforces.com/contest/135/problem/B Description Little Petya v ...

  6. HDU 4217 Hamming Distance 随机化水过去

    Hamming Distance Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others) ...

  7. Xcode更新后插件失效解决办法

    defaults read /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID 获取新版xcode的uuid Xcode6 ...

  8. js跨域请求提示函数未定义的问题

    我的代码是这么写的 window.onload=function(){ function sendRequest(){ var script=document.getElementById(" ...

  9. rpm管理环境包和代码包

    Author: JinDate: 20140610System: CentOS release 6.5 (Final) 06-09-2014c零:问题配置文件问题,不打包使用的配置文件参考配置文件后缀 ...

  10. PWM DAC vs. Standalone

    http://analogtalk.com/?p=534 http://analogtalk.com/?p=551 Posted by AnalogAdvocate on April 09, 2010 ...