N-ary Tree Postorder Traversal - Problem

Given the root of an n-ary tree, return the postorder traversal of its nodes' values.

N-ary tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (see examples).

In postorder traversal, we visit all children nodes first, then the parent node.

Input & Output

Example 1 — Basic N-ary Tree
$ Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]
💡 Note: Postorder visits children first: node 3's children [5,6], then node 3, then nodes 2,4, finally root 1
Example 2 — Deeper Tree
$ 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]
💡 Note: Complex tree with multiple levels - each subtree processed before its parent
Example 3 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Single node tree returns just that node's value

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • 0 ≤ Node.val ≤ 104
  • The height of the n-ary tree is less than or equal to 1000

Visualization

Tap to expand
N-ary Tree Postorder Traversal INPUT 1 3 2 4 5 6 Serialized Input: [1,null,3,2,4,null,5,6] N-ary Tree Structure ALGORITHM STEPS (DFS) 1 Start at Root Begin DFS from node 1 2 Recurse Children Visit all children first 3 Process Leaf Add to result when done 4 Backtrack Add parent after children Traversal Order: Visit 3's children: 5, 6 Then visit 3 Visit 2 (no children) Visit 4 (no children) Finally visit root 1 [5,6] [3] [2] [4] [1] FINAL RESULT Postorder Visit Sequence: 5 1st 6 2nd 3 3rd 2 4th 4 5th 1 6th Output Array: [5,6,3,2,4,1] OK - Verified Children before parent at every level Key Insight: Postorder traversal processes nodes in "children-first, parent-last" order. For N-ary trees, we recursively visit ALL children from left to right, then add the current node to result. Time: O(n) | Space: O(h) where h = tree height for recursion stack TutorialsPoint - N-ary Tree Postorder Traversal | DFS Approach
Asked in
Facebook 15 Google 12 Amazon 8 Microsoft 6
186.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen