这道题的算法思想是:建立一个初始的排序二叉树,然后比较由输入序列建立的另一个二叉树即可。
代码如下:
#include <stdio.h> #include <malloc.h> struct node{/*二叉树的定义*/ int data; struct node *lchild,*rchild; }; struct node *Createtree(struct node *root,int d){/*创建排序二叉树*/ if(root==NULL){ root=(struct node *)malloc(sizeof(struct node)); root->data=d; root->lchild=NULL; root->rchild=NULL; } else{ if(root->data<d)//输入的元素大于根节点,放入右子树中 root->rchild=Createtree(root->rchild,d); else root->lchild=Createtree(root->lchild,d); } return root; }; int Compare(struct node* root,struct node *root1){/*判断两个数是否相等*/ if(root==NULL&&root1==NULL) return 1; else if((root==NULL&&root1!=NULL)||(root!=NULL&&root1==NULL)) return 0; else if(root->data==root1->data) return Compare(root->lchild,root1->lchild)&&Compare(root->rchild,root1->rchild); else return 0; } int main(){ int n,l,d,i; while(scanf("%d %d",&n,&l)&&n!=0){ struct node *root=NULL; for(i=1;i<=n;i++){ scanf("%d",&d); root=Createtree(root,d); } while(l--){ struct node *root1=NULL; for(i=1;i<=n;i++){ scanf("%d",&d); root1=Createtree(root1,d); } if(Compare(root,root1)) printf("Yes\n"); else printf("No\n"); } } return 0; }
