首页 > 代码库 > 借树的遍历一题,尝试非递归三种遍历

借树的遍历一题,尝试非递归三种遍历

#include <iostream>#include <cstdio>#include <cstdlib>#include <stack>using namespace std;int z[30],h[30];class Tree{public:    int data;    Tree *lchild;    Tree *rchild;    Tree()    {        lchild=NULL;        rchild=NULL;    }}*root;Tree *CreatNode(){    Tree *root=new Tree();    return root;}Tree *RestoreTree(int z1,int z2,int h1,int h2){    Tree *root=CreatNode();    root->data=http://www.mamicode.com/h[h2];    for(int i=0;z2-i>=z1;i++)    {        if(z[z2-i]==h[h2])        {            if(i>0)root->rchild=RestoreTree(z2-i+1,z2,h2-i,h2-1);            if(z2-i>z1)root->lchild=RestoreTree(z1,z2-i-1,h1,h2-i-1);            break;        }    }    return root;}void FDpostOrder(Tree *root)///非递归后序遍历。。如果有右儿子就对右子树进行遍历压栈,同时把右二子变成NULL{    stack<Tree*>q;    Tree *temp=root;    while(temp!=NULL||!q.empty())    {        while(temp!=NULL)        {            q.push(temp);            temp=temp->lchild;        }        if(q.top()->rchild!=NULL)///serious        {            temp=q.top()->rchild;            q.top()->rchild=NULL;        }        else        {            cout<<q.top()->data<< ;            q.pop();        }    }}void FDinOrder(Tree *root){    stack<Tree*>q;    Tree *temp=root;    while(temp||!q.empty())///非递归中序遍历,及时栈空了,temp不空,仍然继续    {        while(temp!=NULL)        {            q.push(temp);            temp=temp->lchild;        }        temp=q.top()->rchild;        cout<<q.top()->data<< ;        q.pop();    }}void FDpreOrder(Tree *root)///非递归前序遍历{    stack<Tree*>q;    Tree *temp=root;    while(temp||!q.empty())    {        while(temp!=NULL)        {            q.push(temp);            cout<<temp->data<< ;            temp=temp->lchild;        }        temp=q.top()->rchild;        q.pop();    }}int main(){    int n;    cin>>n;    for(int i=0;i<n;i++)        cin>>h[i];    for(int i=0;i<n;i++)        cin>>z[i];    root=RestoreTree(0,n-1,0,n-1);    FDpreOrder(root);    cout<<endl;    FDinOrder(root);    cout<<endl;    FDpostOrder(root);    cout<<endl;    return 0;}

 

借树的遍历一题,尝试非递归三种遍历