进阶实验4-3.3 完全二叉搜索树 (30分)

 

 解题思路:

1、利用排序树中序遍历非递减的性质,将输入数据升序排序

2、利用完全二叉树的性质,求左子树的个数,从而确定根结点所在位置,递归确定左右子树根结点,建立二叉搜索树

3、层序遍历输出

 

 

#include <stdio.h>
#include <math.h>
#include <malloc.h>
#define ElemType int
typedef struct TNode {
    ElemType Data;
    struct TNode *Left,*Right;
}*BiTree;
int cmp(int *a,int *b) {
    return *a-*b;
}
int FindRoot(int a[],int low,int high) {
    int count;
    if(low==high) {
        count=0;
    } else {
        int len=high+1-low;
        int h=log(len)/log(2);
        int leftnum=len-pow(2,h)+1;
        if(leftnum>pow(2,h)/2)
            leftnum=pow(2,h)/2;
        count=(pow(2,h)-2)/2+leftnum;
    }
    return count;
}
BiTree BuildTree(int a[],int low,int high) {
    int pos=low+FindRoot(a,low,high);
    BiTree T=(BiTree)malloc(sizeof(BiTree));
    T->Data=a[pos];
    int llen=pos-low;
    int rlen=high-pos;
    if(llen) {
        T->Left=BuildTree(a,low,pos-1);
    } else
        T->Left=NULL;
    if(rlen) {
        T->Right=BuildTree(a,pos+1,high);
    } else
        T->Right=NULL;
    return T;
}
int flag=0;
void Out(BiTree T) {
    BiTree Q[100];
    int front=0,rear=0;
    Q[front++]=T;
    while(rear<front) {
        BiTree p=Q[rear++];
        if(flag)
            printf(" ");
        else
            flag=1;
        printf("%d",p->Data);
        if(p->Left)
            Q[front++]=p->Left;
        if(p->Right)
            Q[front++]=p->Right;
    }
}

int main() {
    int n;
    scanf("%d",&n);
    int i;
    int a[n];
    for(i=0; i<n; i++) {
        scanf("%d",&a[i]);
    }
    qsort(a,n,sizeof(int),cmp);
    BiTree T=BuildTree(a,0,n-1);
    Out(T);
}

 

posted @ 2020-03-10 15:04  跃鱼  阅读(398)  评论(0编辑  收藏  举报