link: https://leetcode.com/problems/binary-tree-postorder-traversal/
Solution1: 递归
class Solution {
public void helper(TreeNode root, ArrayList<Integer> res) {
if(root.left != null) helper(root.left, res);
if(root.right != null) helper(root.right, res);
res.add(root.val);
}
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if(root == null) return res;
helper(root, res);
return res;
}
}
Solution2:迭代
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> res = new LinkedList<>();
if(root == null) return res;
stack.add(root);
while(!stack.isEmpty()) {
root = stack.pollLast();
res.addFirst(root.val);
if(root.left != null) {
stack.add(root.left);
}
if(root.right != null) {
stack.add(root.right);
}
}
return res;
}
}