You get root, the top node of a binary tree, and the tree may be empty. List every node's value in postorder: for each node, first everything in its left subtree, then everything in its right subtree, and the node itself last.
Return those values as a list. An empty tree gives an empty list.
Example 1
Input: root = [6, 2, 8, null, 4] Output: [4, 2, 8, 6] Why: 2 waits for its child 4; the root 6 waits for both sides
2 more examples and the constraints
Example 2
Input: root = [5, 3, null, 1, 7] Output: [1, 7, 3, 5] Why: 3 comes after its two children, 5 after everything
Example 3
Input: root = [] Output: [] Why: no nodes, nothing to list
Constraints
- The tree has between 0 and 100 nodes
- −100 ≤ each node value ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- RecursionO(n)
- One stack, last addedO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a tree of 100 nodes | Verdict |
|---|---|---|---|
| Recursion | O(n) | Passes; shortest to write | |
| One stack, last added | O(n) | Best; answers the follow-up |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree. [] must return [], and the code must not touch a null root.
- One node. [-9] returns [-9].
- Only left children. [3, 2, null, 1] pushes the whole chain, then adds 1, 2, 3 as it pops.
- Only right children. [1, null, 2, null, 3] gives [3, 2, 1]: every node waits for the one below it.
Common mistakes
- Popping a node the first time you see it on top, before its right subtree has run.
- Forgetting
last, so after the right child finishes the parent sendsnodeback into it forever. - Adding the node between its subtrees, which gives inorder instead of postorder.
How to talk through it
- 1Clarify. Can the tree be empty? Is recursion allowed, or do they want a loop?
- 2Give the recursion. Left, right, node in three lines; O(n) time and O(h) stack.
- 3Name the hard part. When a node is on top of the stack, you must know whether its right side already ran.
- 4Code the stack with last. Dive left, peek, either go right or append and pop, and keep
lastup to date. - 5Test out loud. Run the empty tree, a left-only chain and a right-only chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?