[Algorithm] Serialize and Deserialize Binary Tree

本文介绍了一种实现二叉树序列化和反序列化的算法,使用递归方式将二叉树转换为字符串,并能从字符串中恢复原始二叉树结构。通过实例演示了如何构建二叉树,对其进行序列化,以及如何从序列化后的字符串进行反序列化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

 

转载于:https://www.cnblogs.com/Answer1215/p/10487181.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值