树---序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树node

 

二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中创建起来的二叉树能够持久保存。序列化能够基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时经过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。

二叉树的反序列化是指:根据某种遍历顺序获得的序列化字符串结果str,重构二叉树。数组

 

方法一:以数组的方式存储函数

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
const arr = [];
function Serialize(pRoot) {
  // write code here
  if (pRoot === null) {
    arr.push('#');
  } else {
    arr.push(pRoot.val);
    Serialize(pRoot.left);
    Serialize(pRoot.right);
  }
}
function Deserialize() {
  // write code here
  let node = null;
  if (arr.length < 1) {
    return null;
  }
  const root = arr.shift();
  if (typeof root === 'number') {
    node = new TreeNode(root);
    node.left = Deserialize();
    node.right = Deserialize();
  }
  return node;
}

 

方法二:以#表示null,!分隔,其实就是至关于在上述数组方法中增长一步将其变为字符串的形式进行存储。this

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} 
function Serialize(r)
{
    if(r === null)
        return "#!";
    var res = "";
    var s = [];
    s.push(r);
    
    while(s.length !== 0){
        var cur = s.pop();
        res += (cur === null) ? "#" : cur.val;
        res += "!";
        if(cur !== null) {
            s.push(cur.right);
            s.push(cur.left);
        }
    }
    return res;
}
function Deserialize(s)
{
    if(s === "")
        return null;
    var arr = s.split("!");
    
    return step(arr);
}

function step(arr) {
    var cur = arr.shift();
    if(cur === "#")
        return null;
    var node = new TreeNode(cur);
    node.left = step(arr);
    node.right = step(arr);
    
    return node;
}
相关文章
相关标签/搜索