二叉树序列化与反序列化

58 阅读1分钟
/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function(root) {
    if (!root) {
        return '';
    }
    const ret = [];
    const nodes = [root];
    while (nodes.length > 0) {
        const node = nodes.shift();
        if (node) {
            ret.push(node.val);
            nodes.push(node.left);
            nodes.push(node.right);
        } else {
            ret.push(null);
        }
    }
    return ret.join(',');
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function(data) {
    if (!data) {
        return null;
    }
    const arr = data.split(',');
    const root = new TreeNode(arr[0]);
    const nodes = [root];
    let point = 1;
    
    while (point < arr.length) {
        const node = nodes.shift();
        
        const leftVal = arr[point];
        const rightVal = arr[point + 1];

        if (leftVal) {
            const leftNode = new TreeNode(leftVal);
            node.left = leftNode;
            nodes.push(leftNode);
        }
        if (rightVal) {
            const rightNode = new TreeNode(rightVal);
            node.right = rightNode;
            nodes.push(rightNode);
        }

        point += 2;
    }

    return root
};