二叉树的非递归遍历(Morris Traversal)

struct TreeNode
{
    int val;
    TreeNode *left,*right;
    TreeNode(int x):val(x),left(NULL),right(NULL){}
};

//前序遍历
vector<int> inorderTraversal(TreeNode *root) 
{
    vector<int> res;
    TreeNode *cur=root,*prev=NULL;
    while(cur) 
    {
        if(!cur->left)
        {
            res.push_back(cur->val);
            cur=cur->right;
        }
        else 
        {
            prev=cur->left;
            while(prev->right&&prev!=cur)prev=prev->right;
            if(!prev->right)
            {
                res.push_back(cur->val);
                prev->right=cur;
                cur=cur->left;
            }
            else
            {
                prev->right=NULL;
                cur=cur->right;
            }
        }
    }
    return res;
}

//中序遍历
vector<int> inorderTraversal(TreeNode *root) 
{
    vector<int> res;
    TreeNode *cur=root,*prev=NULL;
    while(cur) 
    {
        if(!cur->left)
        {
            res.push_back(cur->val);
            cur=cur->right;
        }
        else 
        {
            prev=cur->left;
            while(prev->right&&prev!=cur)prev=prev->right;
            if(!prev->right)
            {
                prev->right=cur;
                cur=cur->left;
            }
            else
            {
                res.push_back(cur->val);
                prev->right=NULL;
                cur=cur->right;
            }
        }
    }
    return res;
}

//后序遍历
void reverse(TreeNode *from,TreeNode *to)
{
    for(TreeNode *x=from,*y=from->right;x!=to;)
    {
        TreeNode *z=y->right;
        y->right=x;
        x=y;
        y=z;
    }
}

void visit(vector<int> &res,TreeNode *from,TreeNode *to)
{
    reverse(from,to);
    for(TreeNode *p=to;;p=p->right)
    {
        res.push_back(p->val);
        if(p==from)break;
    }
    reverse(to,from);
}

vector<int> postorderTraversal(TreeNode *root) 
{
    vector<int> res;
    TreeNode dummy(-1);
    dummy.left=root;
    TreeNode *cur=&dummy,*prev=NULL;
    while(cur) 
    {
        if(!cur->left)cur=cur->right;
        else 
        {
            prev=cur->left;
            while(prev->right&&prev!=cur)prev=prev->right;
            if(!prev->right)
            {
                prev->right=cur;
                cur=cur->left;
            }
            else
            {
                visit(res,cur->left,prev);
                prev->right=NULL;
                cur=cur->right;
            }
        }
    }
    return res;
}

http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html

你可能感兴趣的:(二叉树的非递归遍历(Morris Traversal))