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 <stdio.h>
2#include <stdlib.h>
3
4struct Node {
5 int val;
6 int numChildren;
7 struct Node** children;
8};
9
10void postorderHelper(struct Node* root, int* returnSize, int* result) {
11 if (root == NULL) return;
12 for (int i = 0; i < root->numChildren; i++) {
13 postorderHelper(root->children[i], returnSize, result);
14 }
15 result[(*returnSize)++] = root->val;
16}
17
18int* postorder(struct Node* root, int* returnSize) {
19 int* result = (int*)malloc(10000 * sizeof(int));
20 *returnSize = 0;
21 postorderHelper(root, returnSize, result);
22 return result;
23}
24
This implementation defines a helper function postorderHelper
that performs the recursive traversal. The function visits each child of the current node before appending the node's value to the result array. The main function postorder
initializes the result array and calls the helper function.
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)
1class
Python's iterative solution relies on a stack. Nodes are processed using a stack then prepended to the result list for postorder. A final reversal of result
after processing gives the correct postorder traversal.