算法笔记31:二叉树的序列化和反序列化

140 阅读1分钟

297. 二叉树的序列化与反序列化

我想这道题目被划分到困难应该是因为反序列化的时候可能比较难。我想到采用 BFS 方式进行序列化,维护一个队列不断把元素放进去,然后注意是 null 值也要放进去,因为要确保占位方便后续反序列化的时候追踪元素位置。

反序列化的时候除了要有个队列,也需要维护一个指针,这个指针帮助找到下一个应该处理的元素的位置。在一个个创建节点并连接的同时,移动指针来不断寻找下面的子节点。

const serialize = (root) => {
    if (!root) {
        return '';
    }

    const res = [];
    const queue = [root];

    while (queue.length) {
        const node = queue.shift();
        if (node) {
            queue.push(node.left);
            queue.push(node.right);
            res.push(node.val);
        } else {
            // if it is null then we add nothing
            res.push('');
        }
    }
    
    return `[${res.join(',')}]`;
};

const deserialize = (data) => {
    if (!data) {
        return null;
    }
    
    const list = data.slice(1, data.length - 1).split(',');
    const root = new TreeNode(+list[0]);
    const queue = [root];
    let counter = 1;
    
    while (queue.length) {
        const node = queue.shift();
        if (list[counter] !== '') {
            node.left = new TreeNode(+list[counter]);
            queue.push(node.left);
        }
        // increment the counter after left child
        counter++;
        if (list[counter] !== '') {
            node.right = new TreeNode(+list[counter]);
            queue.push(node.right);
        }
        // increment the counter after right child
        counter++;
    }
    
    return root;
};