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

82 lines
3.2 KiB
Java
Raw Normal View History

2021-06-28 11:06:22 +00:00
Morris Morris
> Github
2021-07-23 15:44:19 +00:00
, `,, , `
2021-06-28 11:06:22 +00:00
![](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<>();
2021-07-23 15:44:19 +00:00
while (!stack.isEmpty() || cur != null) {
2021-06-28 11:06:22 +00:00
//找到当前应该遍历的那个节点
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
//此时指针指向空,也就是没有左子节点,则开始执行出栈操作
TreeNode temp = stack.pop();
arr.add(temp.val);
//指向右子节点
cur = temp.right;
}
return arr;
2021-07-23 15:44:19 +00:00
}
2021-06-28 11:06:22 +00:00
}
```
2021-07-19 15:39:19 +00:00
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
}
}
```
2021-07-23 15:44:19 +00:00
###