public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result=new ArrayList();
Stack<TreeNode> stack=new Stack();
if (root == null) {return result;}
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(0,node.val);
if (node.left != null){
stack.push(node.left);
}
if (node.right != null){
stack.push(node.right);
}
}
return result;
}
}
首先注意到后序遍历就是根右左的反序,那么我们可以用头插法来实现反序,用堆栈来存放根左右的结果,根出栈,头插,左右进栈,由于堆栈是先进后出,所以出栈顺序就是右左,最后的结果就是后序遍历了。