
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.
1using System.Collections.Generic;
2
3public class TreeNode {
4 public int val;
5 public TreeNode left;
6 public TreeNode right;
7 public TreeNode(int x) { val = x; }
8}
9
10public class Solution {
11 public IList<int> PostorderTraversal(TreeNode root) {
12 List<int> result = new List<int>();
13 PostorderHelper(root, result);
14 return result;
15 }
16
17 private void PostorderHelper(TreeNode root, List<int> result) {
18 if (root == null) return;
19 PostorderHelper(root.left, result);
20 PostorderHelper(root.right, result);
21 result.Add(root.val);
22 }
23}The C# solution utilizes a recursive method to perform a postorder traversal. It processes the left and right nodes first, and finally the root node. The method PostorderHelper adds the node values to a list as it traverses the tree in postorder.
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 Java solution adopts a two-stack technique for iterating through the binary tree in postorder traversal without recursion. The first stack processes nodes in a root-right-left order, and subsequently, the second stack outputs the reversed version, producing the expected postorder output.