# Morris Traversal算法遍历BST c实现

Morris Traversal本来是一种中续遍历的经典算法，相对于递归与使用椎的遍历。不需要额外的空间，也就是说空间复杂度为O(1)。
leetcode 中关于二叉树3种遍历方式的题，其中要求不能用递归。那么Morris就是一种可取的方案。

int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int buff[255];
*returnSize=0;
struct TreeNode *cur=root;
struct TreeNode *prev=NULL;
while(cur){
if(cur->left){
prev=cur->left;
while(prev->right && prev->right!=cur)
prev=prev->right;

if(prev->right){
// just come from precessor
prev->right=NULL;
buff[*returnSize]=cur->val;
++(*returnSize);
cur=cur->right;
}else{
prev->right=cur;
cur=cur->left;
}

}else{
buff[*returnSize]=cur->val;
++(*returnSize);
cur=cur->right;
}
}
int bs=sizeof(int)*(*returnSize);
int *res=malloc(bs);

memcpy(res,buff,bs);
return res;
}

int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int buff[255];
*returnSize=0;
struct TreeNode *cur=root;
struct TreeNode *prev=NULL;
while(cur){
if(cur->left){
prev=cur->left;
while(prev->right && prev->right!=cur)
prev=prev->right;

if(prev->right){
// just come from precessor
prev->right=NULL;
cur=cur->right;
}else{
prev->right=cur;
buff[*returnSize]=cur->val;
++(*returnSize);
cur=cur->left;
}

}else{
buff[*returnSize]=cur->val;
++(*returnSize);
cur=cur->right;
}
}
int bs=sizeof(int)*(*returnSize);
int *res=malloc(bs);

memcpy(res,buff,bs);
return res;
}

int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int buff[255];
*returnSize=0;
struct TreeNode dump;
dump.left=root;
dump.right=NULL;
dump.val=0;
struct TreeNode *cur=&dump;
struct TreeNode *prev=NULL;
while(cur){
if(cur->left){
prev=cur->left;
while(prev->right && prev->right!=cur)
prev=prev->right;

if(prev->right){
// just come from precessor
struct TreeNode *p=cur->left;
int rn=0;
while(p!=cur){
buff[*returnSize]=p->val;
++(*returnSize);
p=p->right;
++rn;
}
//reverse right branch vals
int pt=*returnSize -1;
int ph=(*returnSize -rn);
while(pt>ph){
int tmp=buff[ph];
buff[ph]=buff[pt];
buff[pt]=tmp;
--pt;
++ph;
}
prev->right=NULL;
cur=cur->right;
}else{
prev->right=cur;
cur=cur->left;
}

}else{
cur=cur->right;
}
}
int bs=sizeof(int)*(*returnSize);
int *res=malloc(bs);

memcpy(res,buff,bs);
return res;
}

#### 中国大学MOOC-陈越、何钦铭-数据结构-2017春期中考试

2017-04-25 23:03:49

#### 二叉树的五道面试题

2016-11-30 10:14:42

#### Flatten Binary Tree to Linked List -- LeetCode

2014-04-15 01:03:20

#### 二叉搜索树的第K大结点

2017-07-12 15:26:38

#### 二叉搜索树转换为有序双向链表

2014-03-28 00:04:30

#### Morris二叉树遍历算法

2014-03-21 11:42:49

#### Morris方法遍历二叉树

2015-08-29 16:27:40

#### 二叉树神级遍历算法——Morris遍历(C++版)

2015-11-27 14:36:57

#### 二叉树的非递归遍历（Morris Traversal）

2015-05-09 11:32:37

#### LeetCode总结 -- 树的遍历篇

2014-08-12 09:10:07