二叉排序树
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Example Input
2 123456789 987654321 432156789 0
Example Output
NO NO
Hint
Author
#include <bits/stdc++.h>
using namespace std;
int t;
char a[11],b[11];
/*int flag;//设置一个变量计算两棵树有几个节点节点值相同,若等于总共的节点个数则可构成同一二叉排序树*/
typedef struct node
{
char data;
node*left,*right;
} tree;
tree*creat(tree*root,char x)
{
if(root==NULL)///即使在main中已经在root中存了一个点,也要判root此时是否为空,因为新的子树依然可能为空
{
root=new tree;
root->data=x;
root->left=root->right=NULL;
}
else
{
if(x<root->data)
root->left=creat(root->left,x);
else
root->right=creat(root->right,x);
}
return root;
}
int judge(tree*root1,tree*root2)
{
if(root1&&root2)
{
if(root1->data!=root2->data)
return 0;
else if(judge(root1->left,root2->left)&&judge(root1->right,root2->right))///递归调用这个函数就可以判断各个位置上的元素数否相等
return 1;
else
return 0;
}
else if(!root1&&!root2)///两树都空也认为生成了同样的二叉排序树
return 1;
else
return 0;
}
/*void judge(tree*root1,tree*root2)
{
if(root1==NULL||root2==NULL)
{
return;
}
if(root1&&root2)
{
if(root1->data!=root2->data)
return ;
else
{
flag++;
judge(root1->l,root2->l);
judge(root1->r,root2->r);
}
}
}*/
int main()
{
int n,m;
while(scanf("%d",&m)&&m)
{
tree*root1,*root2;
scanf("%s",a);
n=strlen(a);
root1=new tree;///二叉排序树建树最好先建一个头结点。
root1->data=a[0];
root1->left=root1->right=NULL;
for(int i=1; i<n; i++)
root1=creat(root1,a[i]);
while(m--)
{
scanf("%s",b);
root2=new tree;
root2->data=b[0];
root2->left=root2->right=NULL;
for(int i=1; i<n; i++)
root2=creat(root2,b[i]);
t=judge(root1,root2);
if(t==1)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}