# 平时练习题目集-6-21 Is It CBST (30分)

6-21 Is It CBST (30分)

2
i+1为右节点下标 这题为0开头要有改变。

void Insert(int *ret, int num,int index){//数值插入函数但是由于题目数组为0-n-1的，所以要思考左右下标
int left = (index+1)*2-1,right = (index+1)*2;
if(!ret[index])ret[index] = num;
else {
if(num>ret[index]) Insert(ret,num,left);
else Insert(ret,num,right);
}
return;
}
int cnt=0;
void PostOrder(int *ret, int *a, int index){//后序遍历途中按顺序赋值题目要求的输出的A[]，这个写过，但是要注意的是cnt是全局变量，这点我搞了半天。
if(ret[index]){
PostOrder(ret,a,(index+1)*2-1);
PostOrder(ret,a,(index+1)*2);
a[cnt++] = ret[index];
}
}
int IsCBST( int A[], int N ){
int ret[111]={0};
int index=0;
for(int i=0; i<N; i++) Insert(ret,A[i],0);
//    for(int i=0; i<N; i++) printf("%d\n",ret[i]);
PostOrder(ret,A,0);
int flag =1;
for(int i =0; i<N; i++)if(!ret[i])flag = 0;//如果是完全二叉树，则所有的点都在要求的N中，而不是则不然：在ret[x](x>N)的条件下会有节点存在
return flag;
}


Insert a sequence of integer keys into an initially empty binary search tree with larger keys in its left subtree and smaller keys in its right subtree, you are supposed to tell if the resulting tree is a complete binary search tree (CBST), and then return its postorder traversal sequence.
Format of function:

int IsCBST( int A[], int N );

where the sequence of N insertions is stored in A[].

The function IsCBST is supposed to return 1 if the resulting tree is a CBST, or 0 if not. At the mean time, A[] must store the postorder traversal sequence of the resulting tree.
Sample program of judge:

#include <stdio.h>

#define MAXN 10

int IsCBST( int A[], int N );

int main()
{
int A[MAXN], N, i;

scanf("%d", &N);
for (i=0; i<N; i++) scanf("%d", &A[i]);
if ( IsCBST(A, N) ) printf("Yes\n");
else printf("No\n");
for (i=0; i<N; i++) printf("%d ", A[i]);

return 0;


}

09-16 5535

08-01 2万+

07-30 6353

11-18 7932

02-12 8

04-05 18

08-04 895

03-29 252

01-12 3748

08-03 3万+

02-23 3万+

07-22 3万+

10-21 3万+

07-12 4829

06-29 6万+

07-04 6718

09-08 4835

02-16 4792

09-17 6840

03-18 6284

#### 团体程序设计天梯赛-练习集 L1阶段 全部题解

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试