[Algorithm] Serialize and Deserialize Binary Tree

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)
复制代码

 

posted @   Zhentiw  阅读(525)  评论(0编辑  收藏  举报
编辑推荐:
· 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?
点击右上角即可分享
微信分享提示