algorithm-base/animation-simulation/二叉树/二叉树中序遍历(迭代).md

108 lines
3.8 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
> Github
, `,, , `
![](https://cdn.jsdelivr.net/gh/tan45du/test@master/photo/中序遍历.7gct7ztck8k0.gif)
##
![](https://img-blog.csdnimg.cn/20210608010104232.gif)
-
-
list
```java
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> arr = new ArrayList<>();
TreeNode cur = new TreeNode(-1);
cur = root;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || cur != null) {
//找到当前应该遍历的那个节点
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
//此时指针指向空,也就是没有左子节点,则开始执行出栈操作
TreeNode temp = stack.pop();
arr.add(temp.val);
//指向右子节点
cur = temp.right;
}
return arr;
}
}
```
Swift Code
```swift
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var arr:[Int] = []
var cur = root
var stack:[TreeNode] = []
while !stack.isEmpty || cur != nil {
//找到当前应该遍历的那个节点
while cur != nil {
stack.append(cur!)
cur = cur!.left
}
//此时指针指向空,也就是没有左子节点,则开始执行出栈操作
if let temp = stack.popLast() {
arr.append(temp.val)
//指向右子节点
cur = temp.right
}
}
return arr
}
}
```
Go Code:
```go
func inorderTraversal(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
stk := []*TreeNode{}
cur := root
for len(stk) != 0 || cur != nil {
// 找到当前应该遍历的那个节点,并且把左子节点都入栈
for cur != nil {
stk = append(stk, cur)
cur = cur.Left
}
// 没有左子节点,则开始执行出栈操作
temp := stk[len(stk) - 1]
stk = stk[: len(stk) - 1]
res = append(res, temp.Val)
cur = temp.Right
}
return res
}
```
###