树---序列化二叉树

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

 

二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(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,!分隔,其实就是相当于在上述数组方法中增加一步将其变为字符串的形式进行存储。

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;
}

 

posted @ 2020-04-07 09:15  mle123  阅读(244)  评论(0编辑  收藏  举报