判断堆:递归判断每个节点的孩子是否都比其父亲大(小)。

判断BST:中序遍历是否有序。

 1 #include<cstdio>
 2 using namespace std;
 3 #define lc (rt<<1)
 4 #define rc (rt<<1|1)
 5 int T,n,a[1001],b[1001],en;
 6 void Mid(int rt)
 7 {
 8     if(lc<=n) Mid(lc);
 9     b[++en]=a[rt];
10     if(rc<=n) Mid(rc);
11 }
12 bool is_BST()
13 {
14     bool f1=1,f2=1; en=0; Mid(1);
15     for(int i=2;i<=n;i++) if(b[i]<b[i-1]) {f1=0; break;}
16     if(f1) return 1;
17     for(int i=2;i<=n;i++) if(b[i]>b[i-1]) {f2=0; break;}
18     if(f2) return 1;
19     return 0;
20 }
21 bool is_Heap(int rt)
22 {
23     if(lc<=n)
24       {
25           if(a[lc]>a[rt]) return 0;
26           if(!is_Heap(lc)) return 0;
27       }
28     if(rc<=n)
29       {
30           if(a[rc]>a[rt]) return 0;
31           if(!is_Heap(rc)) return 0;
32       }
33     return 1;
34 }
35 bool is_Heap_2(int rt)
36 {
37     if(lc<=n)
38       {
39           if(a[lc]<a[rt]) return 0;
40           if(!is_Heap_2(lc)) return 0;
41       }
42     if(rc<=n)
43       {
44           if(a[rc]<a[rt]) return 0;
45           if(!is_Heap_2(rc)) return 0;
46       }
47     return 1;
48 }
49 int main()
50 {
51     scanf("%d",&T);
52     for(int i=1;i<=T;i++)
53       {
54           printf("Case #%d: ",i);
55           scanf("%d",&n);
56           for(int j=1;j<=n;j++) scanf("%d",&a[j]);
57           bool flag1=0,flag2=0;
58           if(is_BST()) flag1=1;
59           if(is_Heap(1)) flag2=1;
60           if((!flag2)) if(is_Heap_2(1)) flag2=1;
61           if(flag1&&flag2) puts("Both");
62           else if(flag1) puts("BST");
63           else if(flag2) puts("Heap");
64           else puts("Neither");
65       }
66     return 0;
67 }

 

相关文章:

  • 2021-07-20
  • 2021-04-08
  • 2021-08-27
  • 2021-11-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
猜你喜欢
  • 2021-10-24
  • 2021-05-23
  • 2021-08-26
  • 2021-07-23
  • 2022-12-23
  • 2018-06-16
  • 2021-09-12
相关资源
相似解决方案