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

127 lines
4.4 KiB
Java
Raw Normal View History

2021-06-28 10:58:22 +00:00
[]()[]() Morris Morris
## Morris
Morris ,
[]()
![](https://img-blog.csdnimg.cn/20210622155624486.gif)
Morris
![](https://img-blog.csdnimg.cn/20210622142148928.png)
`list.add()`` postMorris() ` list.add() postMorris postMorris Morris
postMorris .
```java
public void postMorris(TreeNode root) {
//反转转链表,详情看下方图片
TreeNode reverseNode = reverseList(root);
//遍历链表
TreeNode cur = reverseNode;
while (cur != null) {
list.add(cur.val);
cur = cur.right;
}
//反转回来
reverseList(reverseNode);
}
//反转链表
public TreeNode reverseList(TreeNode head) {
TreeNode cur = head;
TreeNode pre = null;
while (cur != null) {
TreeNode next = cur.right;
cur.right = pre;
pre = cur;
cur = next;
}
return pre;
}
```
ListNode.next TreeNode.right 线
![](https://img-blog.csdnimg.cn/20210622145335283.png)
绿线
![](https://img-blog.csdnimg.cn/20210622145805876.png)
![](https://img-blog.csdnimg.cn/20210622145846117.png)
```java
class Solution {
List<Integer> list;
public List<Integer> postorderTraversal(TreeNode root) {
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;
}
if (p2.right == null) {
p2.right = p1;
p1 = p1.left;
continue;
} else {
p2.right = null;
postMorris(p1.left);
}
}
p1 = p1.right;
}
//以根节点为起点的链表
postMorris(root);
return list;
}
public void postMorris(TreeNode root) {
//翻转链表
TreeNode reverseNode = reverseList(root);
//从后往前遍历
TreeNode cur = reverseNode;
while (cur != null) {
list.add(cur.val);
cur = cur.right;
}
//翻转回来
reverseList(reverseNode);
}
public TreeNode reverseList(TreeNode head) {
TreeNode cur = head;
TreeNode pre = null;
while (cur != null) {
TreeNode next = cur.right;
cur.right = pre;
pre = cur;
cur = next;
}
return pre;
}
}
```
On O1
Morris