Advanced Experiment 4-3.3 complete binary search tree (30 points)

 

 Problem-solving ideas:

1, using the properties of sort tree traversal sequence of non-decreasing, in ascending order of the input data

2, using the properties of a complete binary tree, find the number of left subtree, the root node to determine the location, left and right subtrees recursively determining the root node, establishing binary search tree

3, the output layer preorder

 

 

#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);
}

 

Guess you like

Origin www.cnblogs.com/snzhong/p/12455764.html