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)
1public class Node {
2 public int val;
public IList<Node> children;
public Node() {}
public Node(int _val) { val = _val; }
public Node(int _val, IList<Node> _children) { val = _val; children = _children; }
}
public class Solution {
public IList<int> Postorder(Node root) {
List<int> result = new List<int>();
if (root == null) return result;
Stack<Node> stack = new Stack<Node>();
stack.Push(root);
while (stack.Count > 0) {
Node node = stack.Pop();
result.Insert(0, node.val);
foreach (var child in node.children) {
if (child != null) stack.Push(child);
}
}
return result;
}
}
C# implementation utilizes a stack approach to perform postorder traversal. As nodes are processed, they are inserted at the start of the result list, ensuring all children are handled first. The order in which nodes are popped and added grants postorder upon completion.