程序:
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct TreeNode *Tree; 4 struct TreeNode{ 5 int v; 6 Tree Left,Right; 7 int flag; 8 }; 9 Tree NewNode(int V){ 10 Tree T=(Tree)malloc(sizeof(struct TreeNode)); 11 T->v = V; 12 T->Left = T->Right=NULL; 13 T->flag=0; 14 return T; 15 } 16 Tree Insert(Tree T,int V){ 17 if(!T) T=NewNode(V); 18 else{ 19 if(V>T->v) 20 T->Right = Insert(T->Right,V); 21 else 22 T->Left = Insert(T->Left,V); 23 } 24 return T; 25 } 26 //读数据建树T 27 Tree MakeTree(int N){ 28 Tree T; 29 int i,V; 30 scanf("%d",&V); 31 T = NewNode(V); 32 for(i=1;i<N;i++){ 33 scanf("%d",&V); 34 T=Insert(T,V); 35 } 36 return T; 37 } 38 //查找结点 39 int check(Tree T,int V){ 40 if(T->flag){ 41 if(V<T->v) return check(T->Left,V); 42 else if(V>T->v) return check(T->Right,V); 43 else return 0; 44 }else{ 45 if(V==T->v){ 46 T->flag = 1; 47 return 1; 48 }else return 0; 49 } 50 } 51 int Judge(Tree T,int N){ 52 int i,V,flag = 0; //flag:0代表目前还不一致,1代表已经不一致 53 scanf("%d",&V); 54 if(V!=T->v) flag = 1; 55 else T->flag = 1; 56 for(i=1;i<N;i++){ 57 scanf("%d",&V); 58 if((!flag)&&(!check(T,V))) flag = 1; 59 } 60 if(flag) return 0; 61 else return 1; 62 } 63 //清除T中各节点flag标记 64 void ResetT(Tree T){ 65 if(T->Left) ResetT(T->Left); 66 if(T->Right) ResetT(T->Right); 67 T->flag = 0; 68 } 69 //释放T的空间 70 void FreeTree(Tree T){ 71 if(T->Left) FreeTree(T->Left); 72 if(T->Right) FreeTree(T->Right); 73 free(T); 74 } 75 //判别是否与T构成一样的树 76 int main(){ 77 int N,L,i; 78 Tree T; 79 scanf("%d",&N); 80 while(N){ 81 scanf("%d",&L); 82 T=MakeTree(N); 83 for(i=0;i<L;i++){ 84 if(Judge(T,N)) printf("Yes "); 85 else printf("No "); 86 ResetT(T); //flag清零 87 } 88 FreeTree(T); //数据清零 89 scanf("%d",&N); 90 } 91 return 0; 92 }
分析:
- 用链表存储树