EasyStackTreeDepth-First SearchBinary Tree

Binary Tree Postorder Traversal

LeetCode
1 approach, code in all languages

You are given the root of a binary tree. Return the values of its nodes visited in postorder sequence.

A postorder traversal visits the entire left subtree, then the entire right subtree, and records the current node last. As a result, every node appears only after all of its descendants, and the root is always the final value emitted.

This children-before-parent ordering is exactly what you need when freeing a tree or computing a value for a node that depends on its subtrees.

Example 1

Input: root = [1,null,2,3]

Output: [3,2,1]

The root's right child 2 has left child 3. We emit 3, then 2, and finally the root 1.

Example 2

Input: root = [1,2,3,4,5]

Output: [4,5,2,3,1]

Left subtree of 1 yields 4,5,2 (children before their parent 2), then the right child 3, then the root 1 last.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now