[Algorithm] Serialize and Deserialize Binary Tree
Given the root to a binary tree, implement
serialize(root), which serializes the tree into a string, anddeserialize(s), which deserializes the string back into the tree.For example, given the following
Nodeclassclass 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的更多相关文章
- [LeetCode] Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...
- LC 297 Serialize and Deserialize Binary Tree
问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...
- [Algorithm] 7. Serialize and Deserialize Binary Tree
Description Design an algorithm and write code to serialize and deserialize a binary tree. Writing t ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- LeetCode——Serialize and Deserialize Binary Tree
Description: Serialization is the process of converting a data structure or object into a sequence o ...
- Serialize and Deserialize Binary Tree
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...
- 297. Serialize and Deserialize Binary Tree
题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...
随机推荐
- springBoot application.properties 基础配置
# 文件编码 banner.charset= UTF-8 # 文件位置 banner.location= classpath:banner.txt # 日志配置 # 日志配置文件的位置. 例如对于Lo ...
- bzoj3456 城市规划 多项式求In
\(n\)个点的无向联通图的个数 打着好累啊 一定要封装一个板子 记\(C(x)\)为无向图个数的指数型生成函数,\(C(0) = 1\) 记\(G(x)\)为无向联通图个数的指数型生成函数,\(G( ...
- BZOJ 3926: [Zjoi2015]诸神眷顾的幻想乡 广义后缀自动机 后缀自动机 字符串
https://www.lydsy.com/JudgeOnline/problem.php?id=3926 广义后缀自动机是一种可以处理好多字符串的一种数据结构(不像后缀自动机只有处理一到两种的时候比 ...
- 拆分Cocos2dx渲染部分代码
纹理实现 思想 这个是Cocos2dx的渲染部分的最基本的实现,被我拆分到mac上,但是并不是用的EGLContext,而是搭配glfw,还有soil第三方图形库. 实现 // // main.cpp ...
- 批量替换url,指定内容不替换
如果需要批量替换url的某几部分,当然是用正则了比如在CI框架中要把 <img src="pc/baidu/aa.jpg"> 替换成 <img src=" ...
- Oracle连接步骤
JDBC实现数据所有的操作: 数据库连接需要的步骤 1.数据库的驱动程序:oracle.jdbc.driver.OracleDriver; 2.连接地址:jdbc:oracle:thin:@主机地址: ...
- 【原】不定义Order属性,通过切面类的定义顺序来决定通知执行的先后顺序
[结论] 在多个切面类的“切入点相同”并且每个切面都“没有定义order属性”的情况下,则切面类(中的通知)的执行顺序与该切面类在<aop:config>元素中“声明的顺序”相关,即先声明 ...
- IP地址便捷修改器 V3.5 绿色版
IP地址便捷修改器 V3.5 绿色版 http://www.downxia.com/downinfo/47786.html#softdown
- Latex Error cannot determine the size of graphic 报错的解决的方法
Latex Error cannot determine the size of graphic 报错的解决的方法 插入jpg文件老是会报错... 追究了半天,原来是编译的命令又问题,不应该使用 la ...
- Arcgis10.5 python按属性分割图层,属性相同分为一个图层
# coding=utf-8 """ Source code for potential gp tool to create outputs based on attri ...