JavaScript in LeetCode format (level-order traversal) using BFS


  • 1
    var serialize = function(root) {
        const res = [];
        const queue = root ? [root] : [];
        while (queue.length) {
            let node = queue.shift();
            if (node) {
                res.push(node.val);
                queue.push(node.left || null);
                queue.push(node.right || null);
            } else {
                res.push(null);
            }
        }
        while (res[res.length - 1] === null) res.pop();
        return JSON.stringify(res);
    };
    
    var deserialize = function(data) {
        const arr = JSON.parse(data);
        if (!arr.length) return null;
        const root = new TreeNode(arr.shift());
        const queue = [root];
        while (queue.length) {
            let node = queue.shift(), val;
            node.left = (val = arr.shift()) || val === 0 ? new TreeNode(val) : null;
            node.right = (val = arr.shift()) || val === 0 ? new TreeNode(val) : null;
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        return root;
    };
    

    While the code is plenty fast, shift can be an O(n) operation depending on the underlying JavaScript engine implementation.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.