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 1212 [HNOI2004]L语言 【AC自动机 + 背包】

    题目链接[http://www.lydsy.com/JudgeOnline/problem.php?id=1212] 题意:给你一些单词,然后给出一个没有标点的文本串S,都是小写字符.现在让你求用给出 ...

  2. 【BZOJ 3661】 Hungry Rabbit (贪心、优先队列)

    3661: Hungry Rabbit Time Limit: 100 Sec  Memory Limit: 512 MBSec  Special JudgeSubmit: 67  Solved: 4 ...

  3. Wannafly挑战赛22游记

    Wannafly挑战赛22游记 幸运的人都是相似的,不幸的人各有各的不幸. --题记 A-计数器 题目大意: 有一个计数器,计数器的初始值为\(0\),每次操作你可以把计数器的值加上\(a_1,a_2 ...

  4. 2、Redis的基础知识

     写在前面的话:读书破万卷,编码如有神 -------------------------------------------------------------------- 主要内容包括: red ...

  5. numpy中的random函数

    1:rand rand(d0, d1, ..., dn)    Random values in a given shape.    Create an array of the given shap ...

  6. git一些命令

    ************git基本命令***************git config --global user.name "xielehe" 设置名字git config - ...

  7. Java_JSP自定义标签的开发与应用

    在JSTL提供了四个标签库(核心标签库.国际化标签库.数据库标签库和XML标签库),涉及到了几十个标签.虽然这些标签可以完成比较复杂的工作,但它们仍然无法满足程序中的特殊需求.因此,就需要用户根据自己 ...

  8. PostgreSQL增强版命令行客户端(pgcli)

    效果: 安装: https://www.pgcli.com/install 官网: https://www.pgcli.com/

  9. Tasker : Task / Shortcut Widgets

    Task / Shortcut Widgets The standard way of running a Tasker task is by attaching it to a profile wh ...

  10. poj 1028 Web Navigation(模拟)

    题目链接:http://poj.org/problem? id=1028 Description Standard web browsers contain features to move back ...