#590

N-ary Tree Postorder Traversal

Easy
StackTreeDepth-First SearchDepth-First SearchStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses an iterative approach with a stack to simulate the postorder traversal without recursion. This is efficient and avoids the overhead of recursive calls.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty stack and push the root node onto it.
  2. 2Step 2: Create an empty list to store the result.
  3. 3Step 3: While the stack is not empty, pop a node from the stack.
  4. 4Step 4: Add the node's value to the result list.
  5. 5Step 5: Push all the children of the popped node onto the stack.
  6. 6Step 6: Reverse the result list before returning it.
solution.py17 lines
1# Full working Python code
2class Node:
3    def __init__(self, val=None, children=None):
4        self.val = val
5        self.children = children if children is not None else []
6
7class Solution:
8    def postorder(self, root):
9        if not root:
10            return []
11        stack = [root]
12        result = []
13        while stack:
14            node = stack.pop()
15            result.append(node.val)
16            stack.extend(node.children)
17        return result[::-1]

Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is linear due to the stack storing nodes.

  • 1Postorder traversal visits children before their parent nodes.
  • 2Using a stack allows us to handle the traversal iteratively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.