#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
typedef struct BNode
{
char data; //数据域
struct BNode *l; //左孩子指针
struct BNode *r; //右孩子指针
}BTNode;
typedef BTNode *Tree;
void CreatexxTree(Tree *root)//前序建树
{
char ch;
cin>>ch;
if(ch=='#')
*root=NULL;
else{
*root=new BTNode;
(*root)->data=ch;
CreatexxTree(&((*root)->l));
CreatexxTree(&((*root)->r));
}
}
void Preorder(Tree root)//前序遍历
{
if(root!=NULL)
{
cout<<root->data;
Preorder(root->l);
Preorder(root->r);
}
}
void Inorder(Tree root)//中序建树
{
if(root!=NULL)
{
Inorder(root->l);
cout<<root->data;
Inorder(root->r);
}
}
void Postorder(Tree root)//后序建树
{
if(root!=NULL)
{
Postorder(root->l);
Postorder(root->r);
cout<<root->data;
}
}
bool DeletePostTree(Tree &root)//后序毁树
{
if(root==NULL)
return true;
else
{DeletePostTree(root->l);
DeletePostTree(root->r);
delete root;
return true;
}
return false;
}
int PostTreeDepth(Tree root)//
{
int hl,hr,max1;
if(root!=NULL)
{
hl=PostTreeDepth(root->l);
hr=PostTreeDepth(root->r);
max1=hl>hr?hl:hr;
return (max1+1);
}
else
return 0;
}
void levelTree(Tree T)
{
vector<BTNode*> vec;
vec.push_back(T);
int cur=0;
int en=1;
while(cur < vec.size())
{
en=vec.size();
while(cur<en)
{
cout<<vec[cur]->data<<' ';
if(vec[cur]->l)
vec.push_back(vec[cur]->l);
if(vec[cur]->r)
vec.push_back(vec[cur]->r);
cur++;
}
}
}
char Prestr[20]="ABCDEFGHIJKLM",Instr[20]="CBEFDGAJIHLKM",Postr[20]="CFEGDBJILMKHA";
void PreInCreateTree(Tree &root,int Pre,int In,int TreeLen)
{
if(TreeLen<=0)
{
root=NULL;
return ;
}
else
{
root=new BTNode;
root->data=Prestr[Pre];
int index=strchr(Instr,Prestr[Pre])-Instr;
int Lenf=index-In;
PreInCreateTree(root->l,Pre+1,In,Lenf);
int Lenr=TreeLen-1-Lenf;
PreInCreateTree(root->r,Pre+Lenf+1,index+1,Lenr);
}
}
void PostInCreateTree(Tree &root,int In,int Post,int TreeLen){
if(TreeLen <= 0)
{
root = NULL;
return;
}
else
{
root = new BTNode;
root->data = Postr[Post];
int index = strchr(Instr,Postr[Post]) - Instr;
int Lenf = index - In;
PostInCreateTree(root->l,In,Post - (TreeLen - 1 - Lenf) - 1,Lenf);
int Lenr = TreeLen - 1 - Lenf;
PostInCreateTree(root->r,index + 1,Post-1,Lenr);
}
}
int main()
{ //freopen("a.txt","r",stdin);
// cin.getline(Prestr,20);
//cin.getline(Instr,20);
// cin.getline(Postr,20);
Tree root;
//PreInCreateTree(root,0,0,strlen(Instr));
// PostInCreateTree(root,0,strlen(Postr)-1,strlen(Instr));
//CreatexxTree(&root);
PostInCreateTree(root,0,strlen(Postr)-1,strlen(Instr));
Preorder(root);
cout<<endl;
Inorder(root);
cout<<endl;
Postorder(root);
cout<<endl;
if(DeletePostTree(root))
cout<<"内存已回收\n";
return 0;
}
树的简单应用
最新推荐文章于 2023-04-26 18:54:56 发布