1. 题目2. 读题(需要重点注意的东西)3. 解法4. 可能有帮助的前置习题5. 所用到的数据结构与算法思想6. 总结
1. 题目
思路(迭代):
要求使用迭代算法
用栈来进行迭代,由于栈是先进后出, 后序遍历为:左 右 根
因此当栈非空时,先将根节点出栈,然后将左节点先进栈,再将右节点进栈
这样进行输出是:根 右 左
对输出进行翻转得到:左 右 根
3. 解法---------------------------------------------------解法---------------------------------------------------:
class Solution {
public List postorderTraversal(TreeNode root) {
List res = new ArrayList<>();
Stack stk = new Stack<>();
if(root == null) return res;
stk.push(root);
while(!stk.isEmpty()){
// 后序遍历: 左 右 根
TreeNode temp = stk.pop();
res.add(temp.val);
// 先加左
if(temp.left != null) stk.push(temp.left);
// 再加右
if(temp.right != null) stk.push(temp.right);
}
// 输出 : 根 右 左
// 倒序 : 左 右 根
Collections.reverse(res);
return res;
}
}
可能存在的问题:
4. 可能有帮助的前置习题[LeetCode]94. 二叉树的中序遍历(java实现)二叉树遍历模板题 5. 所用到的数据结构与算法思想
迭代栈 6. 总结
先序遍历:根 左 右 中序遍历:左 根 右 后序遍历:左 右 根 按 根-右-左 的方式遍历,然后翻转,就能得到后序遍历


![[LeetCode]145. 二叉树的后序遍历(java实现)栈 迭代 [LeetCode]145. 二叉树的后序遍历(java实现)栈 迭代](http://www.mshxw.com/aiimages/31/776599.png)
