-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path04-树4 是否同一棵二叉搜索树.c
110 lines (97 loc) · 1.84 KB
/
04-树4 是否同一棵二叉搜索树.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode *Tree;
struct TreeNode {
int v;
Tree Left, Right;
int flag;
};
Tree NewNode( int V )
{
Tree T = (Tree)malloc(sizeof(struct TreeNode));
T->v = V;
T->Left = T->Right = NULL;
T->flag = 0;
return T;
}
Tree Insert( Tree T, int V )
{
if ( !T ) T = NewNode(V);
else {
if ( V > T->v )
T->Right = Insert( T->Right, V );
else
T->Left = Insert( T->Left, V );
}
return T;
}
Tree MakeTree( int N )
{
Tree T;
int i, V;
scanf("%d", &V);
T = NewNode(V);
for (i = 1; i < N; ++i) {
scanf("%d", &V);
T = Insert(T, V);
}
return T;
}
int check( Tree T, int V )
{
if ( T->flag ) {
if ( V < T->v ) return check(T->Left, V);
else if ( V > T->v ) return check(T->Right, V);
else return 0;
}
else {
if ( V == T->v ) {
T->flag = 1;
return 1;
}
else return 0;
}
}
int Judge( Tree T, int N )
{
int i, V, flag = 0;
scanf("%d", &V);
if ( V != T->v ) flag = 1;
else T->flag = 1;
for (i = 1; i < N; ++i) {
scanf("%d", &V);
if ((!flag) && (!check(T, V))) flag = 1;
}
if (flag) return 0;
else return 1;
}
void ResetT( Tree T )
{
if (T->Left) ResetT(T->Left);
if (T->Right) ResetT(T->Right);
T->flag = 0;
}
void FreeTree( Tree T )
{
if (T->Left) FreeTree(T->Left);
if (T->Right) FreeTree(T->Right);
free(T);
}
int main()
{
int N, L, i;
Tree T;
scanf("%d", &N);
while (N) {
scanf("%d", &L);
T = MakeTree(N);
for (i = 0; i < L; ++i) {
if (Judge(T, N)) printf("Yes\n");
else printf("No\n");
ResetT(T);
}
FreeTree(T);
scanf("%d", &N);
}
return 0;
}