Sponsored
Sponsored
This approach leverages the simplicity of recursion to perform a preorder traversal on an n-ary tree. We start at the root node, then recursively process each child's subtree.
Time Complexity: O(n), where n is the number of nodes in the tree, since we visit each node once.
Space Complexity: O(n) for the recursion stack used in the helper function.
1#include <stdio.h>
2#include <stdlib.h>
3
4// Definition for a Node.
5struct Node {
6 int val;
7 int numChildren;
8 struct Node** children;
9};
10
11void preorderHelper(struct Node* node, int* returnArray, int* returnSize) {
12 if (node == NULL) return;
13 returnArray[(*returnSize)++] = node->val;
14 for (int i = 0; i < node->numChildren; i++) {
15 preorderHelper(node->children[i], returnArray, returnSize);
16 }
17}
18
19int* preorder(struct Node* root, int* returnSize) {
20 *returnSize = 0;
21 int* returnArray = malloc(10000 * sizeof(int)); // Assuming max size
22 preorderHelper(root, returnArray, returnSize);
23 return returnArray;
24}
The C code defines a node structured to represent each tree node with value and children. Using a helper function, preorderHelper
, it ensures the tree is traversed in preorder by accessing each node's value before recursively calling the helper on each child.
This approach uses an explicit stack to simulate the call stack of recursion. We manually manage traversals seen in recursion, starting from the root node, iteratively processing each node, then adding each child to a stack for future visits.
Time Complexity: O(n). Space Complexity: O(n), as most nodes can be stored in the stack in the worst case.
1class
JavaScript’s solution constructs a stack array replicating recursion with iterative needs. With each node processed, it takes its children in reverse order for correct simulated preorder traversal assurance.