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

序列化二叉树 #385

Open
hannah-bingo opened this issue Jan 15, 2023 · 2 comments
Open

序列化二叉树 #385

hannah-bingo opened this issue Jan 15, 2023 · 2 comments

Comments

@hannah-bingo
Copy link
Contributor

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
 // 前序遍历
var serialize = function(root) {
    let str = '';
    let reSerialize = (root) => {
        if (root === null){
            str += '#,'
        } else {
            str += root.val + ',';
            root.left = reSerialize(root.left);
            root.right = reSerialize(root.right);
        }
        return str;
    }
    return reSerialize(root);
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function(data) {
    let arr = data.split(',')
    console.log(arr);

   const reDeserialize = (arr) => {
        if(arr[0] === '#') {
            arr.shift();
            return null;
        }
        const root = new TreeNode(parseInt(arr[0]));
        arr.shift();
        root.left = reDeserialize(arr);
        root.right = reDeserialize(arr);
        return root;
   }
   return reDeserialize(arr);
};

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
@gswysy
Copy link

gswysy commented Apr 24, 2024

var serialize = function(root) {
    return JSON.stringify(root)
};


var deserialize = function(data) {
    return JSON.parse(data)
};

@gswysy
Copy link

gswysy commented Apr 24, 2024

var serialize = function(root) {
    if(!root) return 'N'
    let left = serialize(root.left)
    let right = serialize(root.right)
    return `${root.val},${left},${right}`
};
var deserialize = function(data) {
    const arr = data.split(',')
    function fn(){
        let item = arr.shift()
        if(item==='N') return null
        const root = new TreeNode(item)
        root.left = fn()
        root.right = fn()
        return root
    }
    return fn()
};

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

2 participants