# 二叉树的Morris遍历

## Morris中序遍历

Morris遍历其实就是利用了树中大量的null指针。如下图，我们现在先来考虑中序遍历，对于节点4，什么时候会打印它呢？

### 代码：

void MorrisInOrder(Node* head)
{
return;
// 当前遍历到节点
// 左子树的最右节点
Node* next;
while (cur)
{
// 处理左子树的最右节点
next = cur->left;
if (next)
{
while (next->right && next->right != cur)
next = next->right;
// 不等于cur，说明未遍历过，设置线索，并跳到该左子树
if (next->right != cur)
{
next->right = cur;
cur = cur->left;
continue;
}
// 否则说明该左子树已处理完毕，恢复原指针
else
{
next->right = nullptr;
}
}
// 该节点的左子树已处理完毕，转向右子树
cout << cur->value << " ";
cur = cur->right;
}
}


## 先序遍历

void MorrisPreOrder(Node* head)
{
return;
Node* next;
while (cur)
{
next = cur->left;
if (next)
{
while (next->right && next->right != cur)
next = next->right;
if (next->right != cur)
{
cout << cur->value << " ";
next->right = cur;
cur = cur->left;
continue;
}
else
{
next->right = nullptr;
}
}
else
{
cout << cur->value << " ";
}
cur = cur->right;
}
}


## 后序遍历

### 代码：

Node* ReverseEdge(Node* head)
{
Node* pre = nullptr;
Node* next;
while (cur)
{
next = cur->right;
cur->right = pre;
pre = cur;
cur = next;
}
return pre;
}

{
Node* cur = tail;
while (cur)
{
cout << cur->value << " ";
cur = cur->right;
}
ReverseEdge(tail);
}

{
return;
Node* next;
while (cur)
{
next = cur->left;
if (next)
{
while (next->right && next->right != cur)
next = next->right;
if (next->right != cur)
{
next->right = cur;
cur = cur->left;
continue;
}
else
{
next->right = nullptr;
PrintEdge(cur->left);
}
}
cur = cur->right;
}