JavaScript BFS


  • 0
    G
    var verticalOrder = function(root) {
        const queue = [[root, 0]];
        const nodesByColumn = {};
        
        while (queue.length > 0) {
            const [node, column] = queue.shift();
            
            if (node === null) continue;
            
            if (nodesByColumn[column] === undefined) nodesByColumn[column] = [];
            nodesByColumn[column].push(node.val);
            
            queue.push([node.left, column - 1]);
            queue.push([node.right, column + 1]);
        }
        
        const orderedColumns = Object.keys(nodesByColumn).sort((a, b) => a - b);
        
        return orderedColumns.map(columnKey => {
            return nodesByColumn[columnKey]; 
        });
    };
    

Log in to reply
 

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