数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入
输出
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
提示
这段代码中包含大部分二叉树题的函数,读者可以根据题目变换主函数来做不同的二叉树的题
#include<bits/stdc++.h>
using namespace std;
struct node
{
char data;
struct node *l;
struct node *r;
};
int p;
string c;
struct node *creat(int n,char a[],char b[]) //根据前序中序来还原二叉树的函数
{
struct node *root;
char *p;
if(n==0)
return NULL;
root=(struct node *)malloc(sizeof(struct node));
root->data=a[0];
for(p=b;p!='\0';p++)
if(*p==a[0])
break;
int t;
t=p-b;
root->l=creat(t,a+1,b);
root->r=creat(n-t-1,a+t+1,p+1);
return root;
};
void leavel1(struct node *root) //求叶子的函数
{
p=0;
queue<node *>s;
if(root!=NULL)
s.push(root);
while(!s.empty())
{
root = s.front();
if(!root->r&&!root->l)
{
cout<<root->data;
}
s.pop();
if(root->l)
s.push(root->l);
if(root->r)
s.push(root->r);
}
}
void leavel(struct node *root) //求叶子数的函数
{
p=0;
queue<node *>s;
if(root!=NULL)
s.push(root);
while(!s.empty())
{
root = s.front();
if(!root->r&&!root->l)
{
p++;
}
s.pop();
if(root->l)
s.push(root->l);
if(root->r)
s.push(root->r);
}
}
struct node *creat1() //根据含有逗号的序列求二叉树的函数
{
int i;
struct node *root;
if(c[i++] == ',')
root = NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data = c[i - 1];
root->l = creat1();
root->r = creat1();
}
return root;
}
void middle(struct node *root) //已知二叉树求中序的函数
{
if(root)
{
middle(root->l);
printf("%c",root->data);
middle(root->r);
}
}
void visit(struct node *root) //已知二叉树求层次遍历的函数
{
p=0;
queue<node *>s;
if(root!=NULL)
s.push(root);
while(!s.empty())
{
root = s.front();
cout<<root->data;
s.pop();
if(root->l)
s.push(root->l);
if(root->r)
s.push(root->r);
}
}
void last(struct node *root) //已知二叉树,求后序遍历的函数
{
if(root)
{
last(root->l);
last(root->r);
printf("%c",root->data);
}
}
int depth(struct node *t) //求深度(高度)的函数
{
int ld, rd;
if(!t) return 0;
else
{
ld=depth(t->l);
rd=depth(t->r);
if(ld>rd)
return ld+1;
else
return rd+1;
}
}
int first(struct node *root) //求前(先)序遍历的函数
{
int h,l,r;
if(!root)
return 0;
else
{
l=first(root->l);
r=first(root->r);
if(l>r)
return l+1;
else
return r+1;
}
}
int main()
{
char s1[1000],s2[1000];
int n;
struct node *root;
root=new node;
cin>>n;
while(n--)
{
cin>>s1;
cin>>s2;
int len1=strlen(s1);
root=creat(len1,s1,s2);
last(root);
cout<<endl;
visit(root);
cout<<endl;
}
return 0;
}