Sponsored
Sponsored
This approach utilizes recursion to traverse the N-ary tree in a postorder fashion. For each node, we recursively visit all its children first before processing the node itself.
Time Complexity: O(n), where n is the number of nodes, as each node is visited once.
Space Complexity: O(n) for the recursion stack in the worst case (maximum tree height).
1#include <vector>
2using namespace std;
3
4class Node {
5public:
6 int val;
7 vector<Node*> children;
8
9 Node() {}
10
11 Node(int _val) {
12 val = _val;
13 }
14
15 Node(int _val, vector<Node*> _children) {
16 val = _val;
17 children = _children;
18 }
19};
20
21void postorderHelper(Node* root, vector<int>& result) {
22 if (root == nullptr) return;
23 for (auto child : root->children) {
24 postorderHelper(child, result);
25 }
26 result.push_back(root->val);
27}
28
29vector<int> postorder(Node* root) {
30 vector<int> result;
31 postorderHelper(root, result);
32 return result;
33}
34
The C++ recursive solution uses the postorderHelper
function to perform the traversal. It iterates over each child node recursively before pushing the node's value onto the result vector. The postorder
function initializes a result vector and calls the helper function to perform the traversal.
This approach uses an iterative method to perform postorder traversal with the help of a stack to simulate recursion. Nodes are pushed onto the stack in such a way that their children are processed before the node itself.
Time Complexity: O(n)
Space Complexity: O(n)
1#
This C solution uses a stack to hold nodes and their visitation state. Nodes are pushed onto the stack to revisit them later for value recording, ensuring that each node's children are processed before the node itself, mimicking postorder traversal.