Skip to content

序列化二叉树 #385

@ntting-top

Description

@ntting-top
/**
 * 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));
 */

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions