My Javascript solution


  • 0
    S

    All,

    This is my BFS solution, hope you like it.

    var zigzagLevelOrder = function(root) {
    // Base cases
        if (root === null) return [];
        if (root.left === null && root.right === null) return [[root.val]];
    
        let result = [];
    
    // Zigzag direction
        let goingRight = true;
    
    // BFS
        let queue = [root];
        while (queue.length !== 0) {
            let level = [];
            let size = queue.length;
            for(let i = 0; i < size; i++) {
                let curr = queue.shift();
                level.push(curr.val);
                if (curr.left) queue.push(curr.left);
                if (curr.right) queue.push(curr.right);
            }
    // Reverse the sublevel array if not going from left to right
            if (!goingRight) level.reverse();
            result.push(level);
    
    // Change direction
            goingRight = !goingRight; 
        }
        return result;
    };
    

Log in to reply
 

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