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. BZOJ 2120: 数颜色 带修改的莫队算法 树状数组套主席树

    https://www.lydsy.com/JudgeOnline/problem.php?id=2120 标题里是两种不同的解法. 带修改的莫队和普通莫队比多了个修改操作,影响不大,但是注意一下细节 ...

  2. 【推导】【数学期望】【冒泡排序】Petrozavodsk Winter Training Camp 2018 Day 5: Grand Prix of Korea, Sunday, February 4, 2018 Problem C. Earthquake

    题意:两地之间有n条不相交路径,第i条路径由a[i]座桥组成,每座桥有一个损坏概率,让你确定一个对所有桥的检测顺序,使得检测所需的总期望次数最小. 首先,显然检测的时候,是一条路径一条路径地检测,跳跃 ...

  3. Splay-Tree理解

    简介 splay tree其实就是不停的旋转,没进行一个操作都要进行旋转:例如,当访问某一个结点的时候,会通过旋转其结点使得该结点变为树根,这样保证其的平均复杂度为O(nlogn); 其的操作包括: ...

  4. UVA 2474 - Balloons in a Box 爆搜

    2474 - Balloons in a Box 题目连接: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&a ...

  5. JavaEE-学习目录

    JavaEE ============================================ Web工作机制 JSP Struts基础 Struts核心文件 Struts数据校验与国际化 S ...

  6. Linux性能监控分析命令(五)—free命令介绍

    性能监控分析的命令包括如下:1.vmstat2.sar3.iostat4.top5.free6.uptime7.netstat8.ps9.strace10.lsof 命令介绍:free命令是监控Lin ...

  7. Asky极简教程:零基础1小时学编程,已更新前8节

    Asky极简架构 开源Asky极简架构.超轻量级.高并发.水平扩展.微服务架构 <Asky极简教程:零基础1小时学编程>开源教程 零基础入门,从零开始全程演示,如何开发一个大型互联网系统, ...

  8. xvcd – The Xilinx Virtual Cable Daemon

    http://debugmo.de/2012/02/xvcd-the-xilinx-virtual-cable-daemon/ I recently discovered an almost undo ...

  9. Quartz实现动态定时任务

    一. 说明 由于最近工作要实现定时任务的执行,而且要求定时周期是不固定的,所以就用到了quartz来实现这个功能: spring3.1以下的版本必须使用quartz1.x系列,3.1以上的版本才支持q ...

  10. shell中的括号(小括号,中括号,大括号)及单引号、 双引号,反引号(``)

    一.小括号,园括号() 1.单小括号 () ①命令组.括号中的命令将会新开一个子shell顺序执行,所以括号中的变量不能够被脚本余下的部分使用.括号中多个命令之间用分号隔开,最后一个命令可以没有分号, ...