




Sponsored
Sponsored
The simplest way to perform a postorder traversal of a binary tree is recursively. In postorder traversal, you need to traverse the left subtree, then traverse the right subtree, finally visit the root node. This means visiting the left child, then the right child, and then the node itself for each node in the tree.
Time Complexity: O(n), where n is the number of nodes in the binary tree, because each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack usage.
1function TreeNode(val) {
2    this.val = val;
3    this.left = this.right = null;
4}
5
6var postorderTraversal = function(root) {
7    const result = [];
8    function postorder(node) {
9        if (!node) return;
10        postorder(node.left);
11        postorder(node.right);
12        result.push(node.val);
13    }
14    postorder(root);
15    return result;
16};The JavaScript solution defines a recursive inner function to handle postorder traversal. It ensures nodes are traversed left, then right, ultimately adding the root node value. This function is called from the main function which returns the result once complete.
To perform postorder traversal iteratively, two stacks can be used. The first stack is used to perform a modified preorder traversal (root-right-left), while the second stack reverses this order to provide the postorder traversal (left-right-root). This approach allows the sequence of visiting nodes in postorder traversal without recursion.
Time Complexity: O(n) where n is the number of nodes.
Space Complexity: O(n) due to the usage of two stacks, each containing n nodes in the worst case for balanced or full trees.
This JavaScript solution circumvents recursion by employing two stacks to process the tree. The initial stack (stack1) uses root-right-left sequence collecting nodes, which are subsequently popped from stack2 in reversed order to deliver a left-right-root traversal sequence.