平时练习题目集-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;

}

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试
应支付0元
点击重新获取
扫码支付

支付成功即可阅读