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

142 lines
5.0 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;
}
}
```
Swift Code
```swift
class Solution {
func postorderTraversal(_ root: TreeNode?) -> [Int] {
var list:[Int] = []
var stack:[TreeNode] = []
var cur = root, preNode: TreeNode?
while !stack.isEmpty || cur != nil {
//和之前写的中序一致
while cur != nil {
stack.append(cur!)
cur = cur!.left
}
//1.出栈,可以想一下,这一步的原因。
cur = stack.popLast()
//2.if 里的判断语句有什么含义?
if cur!.right === nil || cur!.right === preNode {
list.append(cur!.val)
//更新下 preNode也就是定位住上一个访问节点。
preNode = cur
cur = nil
} else {
//3.再次压入栈,和上面那条 1 的关系?
stack.append(cur!)
cur = cur!.right
}
}
return list
}
}
```
Go Code:
```go
func postorderTraversal(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
stk := []*TreeNode{}
cur := root
var pre *TreeNode
for len(stk) != 0 || cur != nil {
for cur != nil {
stk = append(stk, cur)
cur = cur.Left
}
// 这里符合本文最后的说法,使用先获取栈顶元素但是不弹出,根据栈顶元素的情况进行响应的处理。
temp := stk[len(stk) - 1]
if temp.Right == nil || temp.Right == pre {
stk = stk[: len(stk) - 1]
res = append(res, temp.Val)
pre = temp
} else {
cur = temp.Right
}
}
return res
}
```
`cur = stack.pop()` `cur = stack.peek()`便
On, On