
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.
1import java.util.ArrayList;
2import java.util.List;
3
4class TreeNode {
5 int val;
6 TreeNode left;
7 TreeNode right;
8 TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12 public List<Integer> postorderTraversal(TreeNode root) {
13 List<Integer> result = new ArrayList<>();
14 postorderHelper(root, result);
15 return result;
16 }
17
18 private void postorderHelper(TreeNode root, List<Integer> result) {
19 if (root == null) return;
20 postorderHelper(root.left, result);
21 postorderHelper(root.right, result);
22 result.add(root.val);
23 }
24}The Java solution uses a recursive helper function to perform the postorder traversal of the binary tree. It adds values to an ArrayList after traversing both left and right subtrees, following the principle of postorder traversal (left-right-root).
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 C implementation uses two stacks: the first stack (stack1) performs a modified preorder traversal (root-right-left); the second stack (stack2) is used to reverse the node visit order to achieve postorder (left-right-root) traversal. Values are ultimately extracted from the second stack.