二叉树实验

来源:互联网 发布:mongodb ubuntu 编辑:程序博客网 时间:2024/05/16 05:26
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <stack>#include <queue>using namespace std;/**/#define ElemType chartypedef struct BiNode{  ElemType data;   struct BiNode *lchild,*rchild;}BiNode,*BiTree;void creatBiTree(BiTree &T){  char c;   cin>>c;   if('#'==c)     T=NULL;    else    {  T=new BiNode;      T->data=c;      creatBiTree(T->lchild);      creatBiTree(T->rchild);    }}int preorder1(BiTree T){   stack<BiTree>s;   s.push(T);//入栈。   while(!s.empty())   {  BiTree u=s.top();      cout<<u->data<<" ";      s.pop();      if(u->rchild!=NULL)        s.push(u->rchild);       if(u->lchild!=NULL)        s.push(u->lchild);   }}int midorder1(BiTree T){   stack<BiTree>S;    BiTree p = T;    while(p || !S.empty())    {        while(p)        {            S.push(p);            p = p->lchild;        }//while结束意味着lson为空        if(!S.empty())        {            cout<<S.top()->data<<' ';            p = S.top()->rchild;            S.pop();        }    }}int preorder(BiTree T){   if(T)  {  cout<<T->data<<" ";      preorder(T->lchild);      preorder(T->rchild);  }}int midorder(BiTree T){   if(T)   {   midorder(T->lchild);       cout<<T->data<<" ";       midorder(T->rchild);   }   return 0;}int postorder(BiTree T){    if(T)   {  postorder(T->lchild);       postorder(T->rchild);       cout<<T->data<<" ";   }   return 0;}int count(BiTree s){    if(!s)     return 0;     if(!s->rchild&&!s->lchild)       return 1;      return count(s->rchild)+count(s->lchild);}int getheight(BiTree s){   if(s)   {   int r=getheight(s->rchild);       int l=getheight(s->lchild);       return (r>l?r:l)+1;   }    return 0;}int ranks(BiTree T){     BiTree p = T;    if(p)    {        queue<BiTree>Q;        Q.push(p);        while(!Q.empty())        {            p = Q.front();            cout<<p->data<<' ';            Q.pop();            if(p->lchild)                Q.push(p->lchild);            if(p->rchild)                Q.push(p->rchild);        }    }    return 0;}int main(){  BiTree T; std::ios::sync_with_stdio(false); //cie::tie(0);  cout<<"请按照二叉树的格式输入"<<endl;    creatBiTree(T);    cout<<endl;    cout<<"二叉树先序遍历(递归)"<<endl;    preorder(T);cout<<endl;    cout<<"二叉树中序遍历(递归)"<<endl;     midorder(T);cout<<endl;    cout<<"二叉树后序遍历(递归)"<<endl;    postorder(T);cout<<endl;    cout<<"二叉树先序遍历非递归版本"<<endl;     preorder1(T);cout<<endl;     cout<<"二叉树中序遍历非递归版本"<<endl;     midorder1(T);cout<<endl;     cout<<"本树的叶子数量"<<endl;     cout<<count(T)<<endl;     cout<<"天有多高??"<<endl;     cout<<getheight(T)<<endl;   cout<<"层次遍历"<<endl;    cout<<ranks(T)<<endl;    return 0;}
原创粉丝点击