x 297. Serialize and Deserialize Binary Tree

LeetCode - The World's Leading Online Programming Learning Platform

time: O(n)

space: O(n)

/**
 * 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}
 */
let arr = [];
var serialize = function (root, idx = 0) {
    arr = [];
    serializeHelper(root);
    return arr.join(',');;
};

function serializeHelper(root, idx = 0) {
    if (root === null) {
        arr.push('null');
        return;
    }

    arr.push(root.val);
    const left = serializeHelper(root.left);
    const right = serializeHelper(root.right);
    return arr;
}

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

function deserializeHelper(arr) {
    if (idx >= arr.length) return null;

    if (arr[idx] === 'null') {
        idx++;
        return null;
    }

    const root = new TreeNode(Number(arr[idx]));
    idx++;
    root.left = deserializeHelper(arr);
    root.right = deserializeHelper(arr);

    return root;
}

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

Last updated