[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
Node
classclass 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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-03-07 [HTML5] a tag, rel="noopener"
2017-03-07 [React] Recompose: Override Styles & Elements Types in React
2017-03-07 [Postgres] Filter Data in a Postgres Table with Query Statements
2017-03-07 [Postgre] Insert Data into Postgre Tables
2017-03-07 [Ramda] Convert Object Methods into Composable Functions with Ramda
2017-03-07 [Django] The admin interface
2016-03-07 [RxJS] Reactive Programming - What is RxJS?