标签:
/*二叉树遍历(递归版本&非递归版本)
(1)中序遍历
(2)先序遍历
(3)后续遍历
*/
struct BinTree {
    int data;             /*数据域*/
    BinTree* leftchild;   /*左孩子*/
    BinTree* rightchild;  /*右孩子*/
};
/*中序遍历(递归版本)*/
void InOrder(BinTree* root)
{
    if(root){
        InOrder(root->leftchild);
        cout << root->data;
        InOrder(root->rightchild);
    }
}
/*先序(递归)*/
void PreOrder(BinTree* root)
{
    if(root){
        cout << root->data;
        PreOrder(root->leftchild);
        PreOrder(root->rightchild);
    }
}
/*后序(递归)*/
void PostOrder(BinTree* root)
{
    if(root){
        PostOrder(root->leftchild);
        PostOrder(root->rightchild);
        cout << root->data;
    }
}
/*先序(非递归)*/
void PreOrder(BinTree* root)
{
    stack<BinTree*> s;   /*模拟系统栈*/
    BinTree* p = root;
    while(p != NULL || !s.empty())
    {
        while(p != NULL)
        {
            cout << p->data;
            s.push(p);
            p = p->leftchild;
        }
        if(!s.empty())
        {
            p = s.top();
            s.pop();
            p = p->rightchild;
        }
    }
}
/*中序(非递归)*/
void InOrder(BinTree* root)
{
    stack<BinTree*> s;
    BinTree* p = root;
    while(p != NULL || !s.empty())
    {
        for( ; p; p = p->leftchild)
            s.push(p);
        if(!s.empty())
        {
            p = s.top();
            s.pop();
            cout << p->data;
            p = p->rightchild;
        }
    }
}
/**/
标签:
原文地址:http://www.cnblogs.com/hzwackerman/p/4804142.html