N-ary Tree Preorder Traversal
LeetCode 775 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Constraints:
- The number of nodes in the tree is in the range `[0, 10^4]`.
- `0 <= Node.val <= 10^4`
- The height of the n-ary tree is less than or equal to `1000`.
Follow up: Recursive solution is trivial, could you do it iteratively?
Topics: Stack, Tree, Depth-First Search
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Stackβ
Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.
Matching brackets, next greater element, evaluating expressions, backtracking history.
Solutionsβ
Solution 1: C# (Best: 432 ms)β
| Metric | Value |
|---|---|
| Runtime | 432 ms |
| Memory | 34.6 MB |
| Date | 2020-01-25 |
/*
// Definition for a Node.
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) {
Stack<Node> preOrder = new Stack<Node>();
List<int> result = new List<int>();
if(root == null) return result;
preOrder.Push(root);
while(preOrder.Count != 0)
{
var popped = preOrder.Pop();
result.Add(popped.val);
for (int i = popped.children.Count-1; i>=0; i--)
{
preOrder.Push(popped.children[i]);
}
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
| Stack | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.
- Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?