1.递归
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
accessTree(root,res);
return res;
}
public void accessTree(TreeNode root, List<Integer> res){
if(root == null){
return;
}
accessTree(root.left,res);
accessTree(root.right,res);
res.add(root.val);
}
2.循环迭代
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode prevAccess = null;
while( root!=null || !stack.isEmpty() ){
while (root !=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right == null || root.right == prevAccess){
res.add(root.val);
prevAccess = root;
root = null;
}else{
stack.push(root);
root = root.right;
}
}
return res;
}