Binary Tree Postorder Traversal
Problem link: https://leetcode.com/problems/binary-tree-postorder-traversal/
Constraint:
Idea:
We could do it either in recursive or iterative way.
Code
- Recursive solution:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> results = new ArrayList<>();
traverse(root, results);
return results;
}
private void traverse(TreeNode root, List<Integer> results) {
if (root == null) {
return;
}
traverse(root.left, results);
traverse(root.right, results);
results.add(root.val);
}
}
2.1 Iterative solution:
Apart from using a Stack, we can use a Set to keep track of all the visited nodes so that we only visit each node once. When deciding whether add current nodes' leftr/right child onto the stack, we first check if it's null or not and then if it's present in the set (which means visited). Only these two conditions are true that we will add them onto the stack.
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> results = new ArrayList<>();
if (root == null) {
return results;
}
Deque<TreeNode> st = new LinkedList<>();
Set<TreeNode> visitedNodes = new HashSet<>();
TreeNode current;
st.addFirst(root);
while (!st.isEmpty()) {
current = st.getFirst();
if (current.left != null && !visitedNodes.contains(current.left)) {
st.addFirst(current.left);
} else if (current.right != null && !visitedNodes.contains(current.right)) {
st.addFirst(current.right);
} else {
st.removeFirst();
results.add(current.val);
visitedNodes.add(current);
}
}
return results;
}
}
Time: O(n).
Space: O(n). The stack would store all the tree elements in worst case. The set would store all the nodes at the end.
2.2 Iterative solution
A better way is based on the fact that post-order traversal is the reverse order of pre-order traversal with visiting the right subtree before the left subtree. We could still use the codes for pre-order traversal, but before returning the results we just need to reverse the collection's order.
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> st = new LinkedList<>();
TreeNode cur = root;
while (cur != null || !st.isEmpty()) {
if (cur != null) {
result.add(cur.val);
st.addFirst(cur);
cur = cur.right;
} else {
cur = st.removeFirst();
cur = cur.left;
}
}
Collections.reverse(result);
return result;
}
}
- Time: O(n).
- Space: O(n).
浙公网安备 33010602011771号