Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its nodes' values: traverse the left subtree, then the right subtree, then visit the node itself.

30:00

Binary Tree Postorder Traversal
easy
Free written solution
Topics
Companies

Given the root of a binary tree, return the postorder traversal of its nodes' values: traverse the left subtree, then the right subtree, then visit the node itself.

Example 1:
Input: {"root":[5,3,8,1,4,7,9]}
Output: [1,4,3,7,9,8,5]
Constraints:
  • The number of nodes in the tree is in the range [0,100][0, 100].

  • −100≤Node.val≤100-100 \leq \text{Node.val} \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[5,3,8,1,4,7,9]}

Put the root 5 on s1. Phase 1 builds root, right, left order on s2; reading s2 backwards is postorder.

phase 1: explore: s1 -> s2
phase 2: reverse: s2 -> res
5381479

s1

to explore

5
→

s2

root, right, left

empty

res (left, right, root)

filled by popping s2, which reverses it

[]

node being moved
on s1
on s2
in res, badge = position
Variables
VariableValue
nodenull
s1[5]
s2[]
res[]
DepthFunction Call
Stack empty
0/26