Javascript Solution (BFS)


  • 0
    G
    var zigzagLevelOrder = (root) => {
        if (!root) {
            return [];
        }
        
        var output = [];
        var queue = [root];
        var isZig = true;
        
        while (queue.length) {
            var temp = [];
            var temp2 = [];
            
            while (queue.length) {
                var current = queue.shift();
                
                temp2.push(current.val);
                
                if (current.right) {
                    temp.push(current.right);
                }
    
                if (current.left) {
                    temp.push(current.left);
                } 
            } 
            
            if (isZig) {
                temp2.reverse();
            }
    
            isZig = !isZig;
    
            queue = temp;
            
            output.push(temp2);
        }
        
        return output;
    };
    

Log in to reply
 

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