public List postorderTraversal(TreeNode root) {
LinkedList ans = new LinkedList<>();
//特殊判断
if(root == null)
return ans;
Deque stack = new ArrayDeque<>();
//加入根节点,既然根节点第一个出来,那顺序就是反的。可以采取头插法,这样最终的顺序就是正确的
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
//头插法;
ans.addFirst(cur.val);
//加入左孩子
if(cur.left != null) {
stack.push(cur.left);
}
//加入右孩子
if(cur.right != null){
stack.push(cur.right);
}
}
return ans;
}