Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

剑指offer_61.序列化二叉树 #165

Open
pengjielee opened this issue Apr 27, 2020 · 0 comments
Open

剑指offer_61.序列化二叉树 #165

pengjielee opened this issue Apr 27, 2020 · 0 comments

Comments

@pengjielee
Copy link
Owner

题目

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

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

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

详解

序列化二叉树
递归遍历二叉树的节点,空节点使用#代替,节点之间使用逗号隔开,返回字符串

反序列化二叉树
设置序号index,将字符串根据逗号分割为数组,根据index的值来设置树节点的val,如果节点的值为#,则返回空的树节点。

JS实现

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Serialize(pRoot)
{
    // write code here
    if(pRoot === null){
        return "#,";
    } else {
        return pRoot.val + ',' + Serialize(pRoot.left) + Serialize(pRoot.right);
    }
}

function Deserialize(str)
{
    // write code here
    if(!str) { return null; }
    return deserialize(str.split(','))
}

function deserialize(arr){
    let node = null;
    const cur = arr.shift();
    if(cur !== '#'){
        node = new TreeNode(cur);
        node.left = deserialize(arr);
        node.right = deserialize(arr);
    }
    return node;
}

More

JavaScript二叉树的序列化与反序列化
https://segmentfault.com/a/1190000019574614

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant