EasyStackTreeDepth-First SearchBinary Tree

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Fitting Order for a Parts Tree is our own problem on the technique behind Binary Tree Postorder Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free