Problem
Given a binary tree, return the postorder traversal of its nodes’ values.
Example:
1 |
|
Follow up: Recursive solution is trivial, could you do it iteratively?
Explanation 1
-
Postorder traversal is from left->right->root.
-
We can use recursion to solve it. First, think of a tree that only has 3 nodes, root node, left and right nodes. Then we want to add the left node first, so we think of another tree and its root node is the previous tree’s left child node, then recursivly, we check this node’s left child, it’s null, we return nothing, then check its right child, which is also null, we return nothing, then we add this root node to the result array. It means when left and right children is null, then we can add that root node (which is the original tree’s left child) to our result array. In other word, we recursivly check the original tree’s left child first, then the right child, then adding the root node.
Solution 1
1 |
|
Explanation 2
- We can also do it iterativly. Similar to 144. Binary Tree Preorder Traversal, preorder is root->left->right. Now postorder is left->right->root, and now we can think of adding the node at the beginning each time, so we want to add root first, then right, then left, in other word, root->right->left, which is similar to preorder. We just need to switch the left and right node from the preorder traversal method.
Solution 2
1 |
|