↓Skip to main content
  1. LeetCode/

LeetCode 590: N-ary Tree Postorder Traversal

·1 min· ·
LeetCode Easy Stack Tree Depth-First-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Runtime Error → Accepted ×5

Approach
#

Post-order handles each child in order and the node last (Tree). An iterative trick: the order “root, last child, …, first child” reversed is exactly post-order. So pop and record, push children in order, and reverse at the end.

My Attempts
#

Attempt 1 used an undefined variable; after that the recursive version passed directly.

Solution
#

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        res, stack = [], [root] if root else []
        while stack:
            node = stack.pop()
            res.append(node.val)
            stack.extend(node.children)
        return res[::-1]

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • The reversal trick requires pushing children in their original order.

Interview Explanation
#

Post-order reversed is root, then children from last to first, so I traverse in that order with a stack and reverse the result. Time O(n).

Related

LeetCode 589: N-ary Tree Preorder Traversal
·2 mins
LeetCode Easy Stack Tree Depth-First-Search
LeetCode 589 note: n-ary pre-order records the node then each child in order; flatten recursive results with extend, not by appending a list
LeetCode 145: Binary Tree Postorder Traversal
·2 mins
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 note: iterative post-order pushes a node back with a visited flag on its first pop, then the right and left children; record it on the second pop
LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first
LeetCode 94: Binary Tree Inorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 note: iterative in-order traversal, pushing nodes while going left, recording on pop, then turning to the right subtree
LeetCode 559: Maximum Depth of N-ary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search
LeetCode 559 note: depth is 1 plus the deepest child, or 1 with no children
LeetCode 563: Binary Tree Tilt
·1 min
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 563 note: return subtree sums in post-order; each node’s tilt is the difference of its subtree sums, added to the answer