You are given an n-ary tree represented as a Node
which has a value and a list of child nodes. Perform a postorder traversal on the tree and return the list of values in postorder sequence.
Example:
Input:
1
/ | \
3 2 4
/ |
5 6
Output: [5, 6, 3, 2, 4, 1]
The Node
structure is defined as:
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
To perform the postorder traversal:
We’ll use a recursive function for this solution as postorder traversal naturally fits a recursive approach.
null
, return immediately as there’s nothing to process.Here’s the C++ implementation of the postorder traversal for an n-ary tree:
#include <vector>
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
void postorderHelper(Node* root, vector<int>& result) {
if (root == nullptr) {
return;
}
for (Node* child : root->children) {
postorderHelper(child, result);
}
result.push_back(root->val);
}
vector<int> postorder(Node* root) {
vector<int> result;
postorderHelper(root, result);
return result;
}
};
The time complexity of this approach is O(n), where n
is the number of nodes in the tree. This is because we visit each node exactly once.
The space complexity is also O(n) due to the recursive call stack and to store the resulting postorder traversal list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?