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.
1using System.Collections.Generic;
public class Node {
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> Preorder(Node root) {
var result = new List<int>();
if (root == null)
return result;
Stack<Node> stack = new Stack<Node>();
stack.Push(root);
while (stack.Count > 0) {
Node currentNode = stack.Pop();
result.Add(currentNode.val);
for (int i = currentNode.children.Count - 1; i >= 0; i--) {
stack.Push(currentNode.children[i]);
}
}
return result;
}
}
The Solution in C# leverages the Stack
provided in .NET to manually handle traversal operations to achieve preorder. This implementation adheres to order by reversing it when adding children to the stack.