#include<bits/stdc++.h>
using namespace std;
#define status char
typedef struct tree{
status data;
struct tree *lchild;
struct tree *rchild;
}tree,*btree;
void CreatTree(btree & tr)
{
status ch;
cin>>ch;
if(ch=='#')
{
tr=NULL ;
}
else{
tr=new tree;
tr->data=ch;
CreatTree(tr->lchild);
CreatTree(tr->rchild);
}
return ;
}
int TreeCount(btree & tr)
{
if(tr==NULL)
return 0;
else
return TreeCount(tr->rchild)+TreeCount(tr->lchild)+1;
}
void PreOrderTree(tree * tr)
{
if(tr==NULL)
{
return ;
}
cout<<tr->data<<" ";
PreOrderTree(tr->lchild);
PreOrderTree(tr->rchild);//cout<<"1";
}
void InOrderTree(tree * tr)
{
if(tr==NULL)
{
return ;
}
InOrderTree(tr->lchild);
cout<<tr->data<<" ";
InOrderTree(tr->rchild);
}
void PostOrderTree(tree * tr)
{
if(tr==NULL)
{
return ;
}
PostOrderTree(tr->lchild);
PostOrderTree(tr->rchild);
cout<<tr->data<<" ";
}
void menu()
{
cout<<"1、初始化二叉树"<<endl<<"2、先序遍历二叉树"<<endl<<"3、中序遍历二叉树"<<endl<<"4、后序遍历二叉树"<<endl<<"5、树的总节点个数"<<endl<<"6、退出程序"<<endl;
}
int main()
{
tree *tre;
menu();
while(1)
{
int n;
cin>>n;
switch(n)
{
case 1:
CreatTree(tre);
break;
case 2:
PreOrderTree(tre);
cout<<endl;
break;
case 3:
InOrderTree(tre);
cout<<endl;
break;
case 4:
PostOrderTree(tre);
cout<<endl;
break;
case 5:
cout<<TreeCount(tre)<<endl;
break;
case 6:
exit(0);
}
}
return 0;
}
数据结构----5、二叉树的建立与前中后序遍历,代码简单易懂
最新推荐文章于 2023-09-20 10:34:37 发布