JavaScript Solution


  • 0
    E
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[][]}
     */
    var zigzagLevelOrder = function(root) {
        const pushArr = function (rootTree,arr) {
            if (rootTree && rootTree.left !== null) arr.push(rootTree.left);
            if (rootTree && rootTree.right !== null) arr.push(rootTree.right);
        }
        
        if(!root) return [];
        
        let result = [];
        let stack = [root];
    
        while (stack.length !== 0) {
            const tempArr = [];
            
           stack.map(val => {
              tempArr.push(val.val)
           })
            
            let newStack  = [];
            
            stack.map(val => {
                pushArr(val,newStack);
            })
            
            stack = newStack;
            
            result.push(tempArr);
        }
        
        result = result.map(function(val,index){
            if((index+1) % 2 === 0) {
                val.reverse();
            }
            return val;
        })
        
        
        return result;
        
    };
    

Log in to reply
 

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