--- sequence of binary tree

Implement two functions are used to serialize and deserialize binary

 

It refers to a sequence of binary: the binary tree is saved in a format string in accordance with the result of a traversing manner such that the memory can be set up binary persisted. Serialization may be based on the first order, in sequence, after, the binary tree traversal sequence is modified, the sequence of the result is a string representing the blank nodes (#) by some sequences of symbol to! End node represents a value (value!).

Deserialized binary tree means: The serialized string str some results obtained traversal order to reconstruct a binary tree.

 

Method a: stored as arrays

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

 

Method Two: The # indicates null ,! Separated, in fact, equivalent to an increase step will be to turn it into a string stored in the array process.

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

 

Guess you like

Origin www.cnblogs.com/mlebk/p/12651402.html