oneby7

Binary Trees Traversals

340. Binary Tree Postorder Traversal

Easy

You are given root, the root node of a binary tree. Return the values of all its nodes in postorder.

Postorder lists a node after the nodes below it. It lists the root's whole left subtree in postorder, then its whole right subtree in postorder, and the root comes last. A missing subtree adds nothing, and an empty tree gives [].

Leave the tree as you found it. When your function returns, every node must still have its own value and its own two children.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

12346911

Input: root = [6, 2, 9, 1, 4, null, 11, null, null, 3]

Output: [1,3,4,2,11,9,6]

Explanation: The left subtree of 6 comes first: 1, then 4's child 3, then 4, then 2 after both its children. The right subtree comes next: 11, then 9. The root 6 comes last.

Example 2

Input: root = []

Output: []

Explanation: The tree has no nodes, so there is nothing to list.

Example 3

-5−10⁹10⁹

Input: root = [-5, null, 1000000000, -1000000000]

Output: [-1000000000,1000000000,-5]

Explanation: −5 has no left subtree, so its right subtree comes first. In it, the left child −1000000000 comes before its parent 1000000000. Then comes −5.

Check your understanding

Work out the answer for this input before you write any code.

root = [8, 3, 5, 7, null, 2, 4]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.