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

6-21 Is It CBST (30分)
有帮助的话 请双击666 加三连哦! :)
用普通数值建树解决
标准情况下 假设i(1开头)为根节点下标,则2i为左节点下标
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;

}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值