樹---序列化二叉樹

請實現兩個函數,分別用來序列化和反序列化二叉樹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;
}
相關文章
相關標籤/搜索