九度OJ 教程36 排序二叉树的建立与比较是否相同。

来源:互联网 发布:下载流星网络电视 编辑:程序博客网 时间:2024/06/02 04:33

题目地址:http://ac.jobdu.com/problem.php?cid=1040&pid=35


//九度OJ 教程36 排序二叉树的建立与比较是否相同。//http://ac.jobdu.com/problem.php?cid=1040&pid=35#include <stdio.h>#include<string.h>#include<malloc.h>typedef struct tt{char data;struct tt *l,*r;}tt,*tp;int flag;//全局变量,标记排序树是否相等。void tfree(tt *root){if(root==NULL)return;tfree(root->l);tfree(root->r);free(root);}int comp(tt *root,tt *root1){if(root==NULL&&root1==NULL)return 1;if(root==NULL||root1==NULL)return 0;//由于上个语句有return 1,则这个如果成立的话便是有且只有一个为NULL。if(root->data!=root1->data)return 0;return ((comp(root->l,root1->l))&&(comp(root->r,root1->r)));}int main(){int n;tp root=NULL,root1=NULL;tp p=NULL,q2=NULL,q1=NULL;int i,j,k,l;char hh[10];while(~scanf("%d",&n)&&n){root=(tt *)malloc(sizeof(tt));scanf("%s",hh);l=strlen(hh);root->l=root->r=NULL;root->data=hh[0];for(i=1;i<l;i++){q1=NULL;q2=root;p=(tt *)malloc(sizeof(tt));p->l=p->r=NULL;p->data=hh[i];while(q2!=NULL){if(p->data>q2->data){q1=q2;q2=q2->r;}else{q1=q2;q2=q2->l;}}if(p->data>q1->data){q1->r=p;}else q1->l=p;}for(j=0;j<n;j++){root1=(tt *)malloc(sizeof(tt));scanf("%s",hh);l=strlen(hh);root1->l=root1->r=NULL;root1->data=hh[0];for(i=1;i<l;i++){q1=NULL;q2=root1;p=(tt *)malloc(sizeof(tt));p->l=p->r=NULL;p->data=hh[i];while(q2!=NULL){if(p->data>q2->data){q1=q2;q2=q2->r;}else{q1=q2;q2=q2->l;}}if(p->data>q1->data){q1->r=p;}else q1->l=p;}flag=comp(root,root1);if(flag)printf("YES\n");else printf("NO\n");tfree(root1);}tfree(root);}return 0;}


原创粉丝点击