Skip to content
Problem 590 · LeetCode 590(opens in a new tab)

N-ary Tree Postorder Traversal

EasyStacks

You are given the root of a tree where each node can have any number of children, ordered from left to right. Return the node values in postorder: for every node, first list the subtrees of all its children, from left to right, and only then the node itself.

The examples write a tree level by level: the root, a null, then the children of each node as one group, every group ending with a null.

Example 1

Input:  root = [5, null, 3, 9, null, 2, 8, 1, null, 6]
Output: [2, 8, 1, 3, 6, 9, 5]
Why:    3's children, then 3, then 9's child, then 9, then the root
2 more examples and the constraints

Example 2

Input:  root = []
Output: []
Why:    an empty tree has no nodes

Example 3

Input:  root = [11]
Output: [11]
Why:    a lone root is its own postorder

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • 0 ≤ node value ≤ 10,000
  • The tree is at most 1,000 levels deep

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. RecursionO(n)
  2. Stack, then reverseO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
RecursionO(n)
Shortest; uses the call stack
Stack, then reverseO(n)
Best; iterative, no depth limit

n = number of nodes, h = height of the tree. Same work; the stack version adds one cheap reverse.

Edge cases to test

  • Empty tree. root is null: return an empty list.
  • One node. [11] gives [11].
  • A long chain. A 1,000-level chain comes out bottom to top; recursion goes 1,000 calls deep.
  • A wide root. A root with many children lists them left to right, then the root.
  • Repeated values. Values can repeat; the order is decided by position, not value.

Common mistakes

  • Pushing the children in reverse, as in preorder; after the final reverse the children come out right to left.
  • Forgetting the final reverse, which returns the mirror of postorder.
  • Writing the node before its children, which is preorder.

How to talk through it

  1. 1Clarify. Can the tree be empty? Are the children ordered? Is recursion allowed?
  2. 2Give the recursion. Visit every child, then write the node. O(n) time, O(h) call stack.
  3. 3Turn it around. Postorder reversed is the node first, then children right to left: an easy stack walk.
  4. 4Code the stack. Pop, append, push children left to right; reverse at the end.
  5. 5Test out loud. Run the empty tree, a single node and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?