
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.
1#include <vector>
2using namespace std;
3
4struct TreeNode {
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11void postorderHelper(TreeNode* root, vector<int>& result) {
12 if (root == nullptr) return;
13 postorderHelper(root->left, result);
14 postorderHelper(root->right, result);
15 result.push_back(root->val);
16}
17
18vector<int> postorderTraversal(TreeNode* root) {
19 vector<int> result;
20 postorderHelper(root, result);
21 return result;
22}This C++ solution involves a recursive helper method, postorderHelper, to carry out postorder traversal on the binary tree. It pushes values into a vector once both the left and right subtrees are traversed. Thus ensuring the nodes are traversed in postorder: 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.