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. QT学习笔记3:QT中语法说明

    一.Qt 类中Q_OBJECT的作用 QObject 是所有Qt对象的基类. QObject 是Qt模块的核心.它的最主要特征是关于对象间无缝通信的机制:信号与槽.使用connect()建立信号到槽的 ...

  2. wpf企业应用之带选项框的TreeView

    wpf里面实现层次绑定主要使用HierarchicalDataTemplate,这里主要谈一谈带checkbox的treeview,具体效果见 wpf企业级开发中的几种常见业务场景. 先来看一下我的控 ...

  3. [BZOJ 4809] 相逢是问候

    Link: 传送门 Solution: 以前没见过的套路题…… 1.使用EXT欧拉定理降幂的套路: $a^{x}=a^{xmod\phi(P)+\phi(P)} mod P$,且$x\ge P$ 这样 ...

  4. Siege(开源Web压力测试工具)——多线程编程最佳实例

    在英语中,"Siege"意为围攻.包围.同时Siege也是一款使用纯C语言编写的开源WEB压测工具,适合在GNU/Linux上运行,并且具有较强的可移植性.之所以说它是多线程编程的 ...

  5. 【10.5校内测试】【DP】【概率】

    转移都很明显的一道DP题.按照不优化的思路,定义状态$dp[i][j][0/1]$表示吃到第$i$天,当前胃容量为$j$,前一天吃(1)或不吃(0)时能够得到的最大价值. 因为有一个两天不吃可以复原容 ...

  6. poj 1330 Nearest Common Ancestors 单次LCA/DFS

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 19919   Accept ...

  7. HashMap和Hashtable的区别--List,Set,Map等接口是否都继承自Map接口--Collection和Collections的区别

    面试题: 1.HashMap和Hashtable的区别? HashMap:线程不安全,效率高,键和值都允许null值 Hashtable:线程安全,效率低,键和值都不允许null值 ArrayList ...

  8. 华为S5300系列交换机V100R005SPH020升级补丁

    S23_33_53-V100R005SPH020.pat 附件: 链接:https://pan.baidu.com/s/1-qgNEtRsZbNnC4eK4DTctA  密码:wpn3

  9. Accessing an element's parent with ElementTree(转)

    Today I ran across a situation where I needed to programmatically remove specific elements from a KM ...

  10. 分频器VHDL描述

    在数字电路中,常需要对较高频率的时钟进行分频操作,得到较低频率的时钟信号.我们知道,在硬件电路设计中时钟信号时非常重要的.    下面我们介绍分频器的VHDL描述,在源代码中完成对时钟信号CLK的2分 ...