Simple JavaScript solution


  • 0

    A postorder traversal can be easily reversed by a preorder traversal like this:

    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var postorderTraversal = function(root) {
        if (!root) return [];
        
        var result = [], stack = [root];
        
        while (stack.length) {
            var node = stack.pop();
            // insert the node val to the front
            result.unshift(node.val);
    
            if (node.left) stack.push(node.left); // left first
            if (node.right) stack.push(node.right); // then right
        }
        
        return result;
    };
    

Log in to reply
 

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