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.
1using System.Collections.Generic;
2
3public class Node {
4 public int val;
5 public IList<Node> children;
6
7 public Node() {}
8
9 public Node(int _val) {
10 val = _val;
11 }
12
13 public Node(int _val, IList<Node> _children) {
14 val = _val;
15 children = _children;
16 }
17}
18
19public class Solution {
20 public IList<int> Preorder(Node root) {
21 var result = new List<int>();
22 PreorderHelper(root, result);
23 return result;
24 }
25
26 private void PreorderHelper(Node node, IList<int> result) {
27 if (node == null) return;
28 result.Add(node.val);
29 foreach (var child in node.children) {
30 PreorderHelper(child, result);
31 }
32 }
33}
In C#, the solution employs a helper method PreorderHelper
, which recursively processes each node value and traverses its children's nodes, storing results in a list to construct the preorder traversal.
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.
1
This C solution uses a stack structure to handle the iterative traversal. The stack manually manages nodes left to process, with each node added to the result upon visitation. It handles children in reverse order to maintain correct preorder evaluation.