algorithm-base/animation-simulation/二叉树/二叉树的后续遍历 (迭代).md

82 lines
3.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

[]()[]() Morris Morris
##
![](https://cdn.jsdelivr.net/gh/tan45du/test@master/photo/后序遍历.2bx6qccr1q1w.gif)
,` , , , `
``
1.
2.?
![](https://img-blog.csdnimg.cn/20210622160754912.gif)
1.
> 访 cur right 访访 cur
2.
> cur right null cur.right 访 `cur.right != preNode `
>
> `cur = cur.right`
```java
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
TreeNode cur = root;
//这个用来记录前一个访问的节点,也就是橙色箭头
TreeNode preNode = null;
while (cur != null || !stack.isEmpty()) {
//和之前写的中序一致
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
//1.出栈,可以想一下,这一步的原因。
cur = stack.pop();
//2.if 里的判断语句有什么含义?
if (cur.right == null || cur.right == preNode) {
list.add(cur.val);
//更新下 preNode也就是定位住上一个访问节点。
preNode = cur;
cur = null;
} else {
//3.再次压入栈,和上面那条 1 的关系?
stack.push(cur);
cur = cur.right;
}
}
return list;
}
}
```
`cur = stack.pop()` `cur = stack.peek()`便
On, On