Accepted Javascript recursive solution


  • 0
    R

    Any feedback on improvements is welcomed!

    function largestValues(root, vals = [], queue = { 0: [ root ] }, depth = 0) {
        if (!root) {
            return vals;
        }
        
        while (queue[ depth ].length) {
            var nodes = queue[ depth ];
    
            if (!queue.hasOwnProperty(depth + 1)) {
                queue[ depth + 1 ] = [];
            }
    
            var largest = -Infinity;
    
            nodes.forEach(function(node) {
                node && node.left && queue[ depth + 1 ].push(node.left);
                node && node.right && queue[ depth + 1 ].push(node.right);
            });
    
            vals.push(largestNode(nodes));
    
            delete queue[ depth++ ];
        }
    
        return vals;
    }
    
    function largestNode(nodes) {
        return nodes.reduce(function(largest, node) {
            if (node && node.val > largest) {
                largest = node.val;
            }
    
            return largest;
        }, -Infinity);
    }
    
    

Log in to reply
 

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