Accepted Javascript solution


  • 0
    R

    Any comments on improvement are welcomed!

    function zigzagLevelOrder(root, depth = 0, queue = { 0: [ root ] }, nodes = []) {
        if (!root) {
            return [];
        }
    
        while (queue[ depth ].length) {
            var currNodes = queue[ depth ];
    
            if (!queue[ depth + 1 ]) {
                queue[ depth + 1 ] = [];
            }
    
            nodes.push(lvlNodes(queue, depth, currNodes));
    
            delete queue[ depth++ ];
        }
    
        return nodes;
    }
    
    function lvlNodes(queue, depth, currNodes) {
        return currNodes.reduce(function(lvlNodes, node, i) {
            if (depth % 2 === 0) {
                lvlNodes.push(node.val);
            } else {
                lvlNodes.push(currNodes[ (currNodes.length - 1) - i ].val);
            }
    
            node.left && queue[ depth + 1 ].push(node.left);
            node.right && queue[ depth + 1 ].push(node.right);
    
            return lvlNodes;
        }, []);
    }
    

Log in to reply
 

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