binary-tree
depth-first-search
recursion
stack

Given the root of a binary tree, return its postorder traversal as an array of node values. Postorder means you visit the left subtree first, then the right subtree, and then the current node.

If the tree is empty, return an empty array. The example below shows the required order, and the constraints and follow-up appear afterward.

Input / output

  • Input: root: TreeNode (the JSON test fixture is a LeetCode-style level-order array, e.g. [1,null,2,3], using null for missing children)
  • Output: int[]

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

Follow-up

The recursive solution is the clearest starting point, but can you also solve it iteratively using a single stack? An iterative solution without a second stack is trickier because you need to know when a node's right subtree has already been processed.

Examples

Example 1

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

Example 2

Input: root = []
Output: []

Example 3

Input: root = [1]
Output: [1]