N-ary Tree Postorder Traversal — LeetCode 590 Python Solution

EasyStackTreeDepth-First Search
Problem
#590
Pattern
Stack
Reading time
4 min

The problem

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.

Example

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

Python solution

Python
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""


class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        def dfs(root):
            if root is None:
                return
            for child in root.children:
                dfs(child)
            ans.append(root.val)

        ans = []
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 590. N-ary Tree Postorder Traversal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 590. N-ary Tree Postorder Traversal?
LeetCode 590. N-ary Tree Postorder Traversal is rated Easy on LeetCode.
What is the time complexity of LeetCode 590. N-ary Tree Postorder Traversal?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 590. N-ary Tree Postorder Traversal?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 590. N-ary Tree Postorder Traversal cover?
LeetCode 590. N-ary Tree Postorder Traversal is tagged Stack, Tree and Depth-First Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview