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

105 lines
3.6 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
} else {
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
Morris `p2.right == p1` p1 `list.add(p1.val);`
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;
continue;
} else {
p2.right = null;
}
}
list.add(p1.val);
p1 = p1.right;
}
return list;
}
}
```