1. Recursive DFS Postorder Traversal
Intuition
Recursively visit left subtree, then right subtree, then append node.val to result.
When to apply: Standard implementation.
Algorithm
- Step 1: If root is null, return.
- Step 2: dfs(root.left).
- Step 3: dfs(root.right).
- Step 4: Append root.val to result.
- Step 5: Return result.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* root, vector<int>& ans) { if (!root) return; dfs(root->left, ans); dfs(root->right, ans); ans.push_back(root->val); } vector<int> postorderTraversal(TreeNode* root) { vector<int> ans; dfs(root, ans); return ans; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Visits each node once in O(n) time. - Space complexity:
O(h)— Call stack depth O(h).