Skip to main content

N-ary Tree Postorder Traversal

LeetCode 776 | Difficulty: Easy​

Easy

Problem Description​

Given the root of an n-ary tree, return the postorder 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: [5,6,3,2,4,1]

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: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]

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.

When to use

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.

When to use

Matching brackets, next greater element, evaluating expressions, backtracking history.


Solutions​

Solution 1: C# (Best: 380 ms)​

MetricValue
Runtime380 ms
Memory34.7 MB
Date2020-01-25
Solution
/*
// 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> Postorder(Node root) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
List<int> result = new List<int>();
if(root==null) return result;
s1.Push(root);
while(s1.Count != 0)
{
var popped = s1.Pop();
s2.Push(popped);
foreach (var child in popped.children)
{
s1.Push(child);
}
}
while(s2.Count!=0)
{
result.Add(s2.Pop().val);
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$
Stack$O(n)$$O(n)$

Interview Tips​

Key Points
  • 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?