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

134 lines
4.3 KiB
Java
Raw Normal View History

2021-06-28 10:58:22 +00:00
### **Morris**
Morris Morris
Morris
** Morris **
```java
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
TreeNode p1 = root; TreeNode p2 = null;
while (p1 != null) {
p2 = p1.left;
if (p2 != null) {
//找到左子树的最右叶子节点
while (p2.right != null && p2.right != p1) {
p2 = p2.right;
}
//添加 right 指针,对应 right 指针为 null 的情况
//标注 1
if (p2.right == null) {
list.add(p1.val);
p2.right = p1;
p1 = p1.left;
continue;
}
//对应 right 指针存在的情况,则去掉 right 指针
p2.right = null;
//标注2
2021-07-23 15:44:19 +00:00
} else {
2021-06-28 10:58:22 +00:00
list.add(p1.val);
}
//移动 p1
p1 = p1.right;
}
return list;
}
}
```
1 p1 p1 list
![image](https://cdn.jsdelivr.net/gh/tan45du/test@master/image.3h60vcjhqo80.png)
p1 `p1 = p1.left`
![](https://cdn.jsdelivr.net/gh/tan45du/test@master/image.44fk4hw4maw0.png)
`p2.right == p1` `p2.right == null` `p1 = p1.right`, p1
2021-07-23 15:44:19 +00:00
Morris `p2.right == p1` p1 `list.add(p1.val);`
2021-06-28 10:58:22 +00:00
Morris
![](https://img-blog.csdnimg.cn/20210622155624486.gif)
![Morris](https://img-blog.csdnimg.cn/20210622155959185.gif)
****
```java
//中序 Morris
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
TreeNode p1 = root;
TreeNode p2 = null;
while (p1 != null) {
p2 = p1.left;
if (p2 != null) {
while (p2.right != null && p2.right != p1) {
p2 = p2.right;
}
if (p2.right == null) {
p2.right = p1;
p1 = p1.left;
2021-07-23 15:44:19 +00:00
continue;
2021-06-28 10:58:22 +00:00
} else {
p2.right = null;
}
}
list.add(p1.val);
p1 = p1.right;
}
return list;
}
}
```
2021-07-19 15:54:09 +00:00
Swift Code
```swift
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var list:[Int] = []
guard root != nil else {
return list
}
var p1 = root, p2: TreeNode?
while p1 != nil {
p2 = p1!.left
if p2 != nil {
while p2!.right != nil && p2!.right !== p1 {
p2 = p2!.right
}
if p2!.right == nil {
p2!.right = p1
p1 = p1!.left
continue
} else {
p2!.right = nil
}
}
list.append(p1!.val)
p1 = p1!.right
}
return list
}
}
```