Clean JavaScript solution


  • 0
    D
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var postorderTraversal = function(root) {
        
        if(!root){
            return [];
        }
        
        let arr = [];
        
        let stack = [];
        let stackTop = 0;
        stack.push(root);
        
        while(stackTop >= 0){
            let peek = stack[stack.length-1];
            if(peek.left && !peek.left.isDone){
                stack.push(peek.left);
                stackTop++;
                continue;
            }
            
            if(peek.right && !peek.right.isDone){
                stack.push(peek.right);
                stackTop++;
                continue;
            }
            
            let pop = stack.pop();
            pop.isDone = true;
            arr.push(pop.val);
            stackTop--;
            
        }
        
        
        return arr;
        
        
    };
    
    
    

Log in to reply
 

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