您的位置:首页 > 理论基础 > 数据结构算法

2136 数据结构实验之二叉树的建立与遍历

2016-11-03 16:50 573 查看
数据结构实验之二叉树的建立与遍历

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
char a1[100],a2[100];
struct node
{
int data;
struct node *lchild,*rchild;
};
struct node *creat(int n,char *a1,char *a2)
{
struct node*root;
int i;
if(n==0)
return NULL;
root = (struct node*)malloc(sizeof(struct node));
root->data=a2[n-1];
for(i=0;i<n;i++)
{
if(a1[i]==a2[n-1])
break;
}
root->lchild=creat(i,a1,a2);
root->rchild=creat(n-i-1,a1+1+i,a2+i);
return root;
};
int depth(struct node *root)
{
int ld,rd,depthval;
if(!root)
depthval = 0;
else
{
ld=depth(root->lchild);
rd=depth(root->rchild);
depthval=1+(ld>rd?ld:rd);
}
return depthval;
}
int main()
{
int t,len;
ios::sync_with_stdio(false);cin.tie(0);  //提高C++输入输出的方法    use '\n' or"\n"   instead.such as : cout<<n<<" "<<m<<"\n";
struct node *root;
while (cin>>t)
{
while(t--)
{
cin>>a1;
cin>>a2;
len=strlen(a1);
root=creat(len,a1,a2);
cout<<depth(root)<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: