进阶实验4-3.4 笛卡尔树 (25分)--二叉排序树+堆排序

 

 解题思路:

1、首先找出根结点,建二叉树

2、先判断是否是二叉排序树

      如果是,则判断是否满足堆排序的要求

      否则,退出

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAX 1000
#define INF_MIN 0xc0c0c0c0
typedef enum {false,true
             } bool;
typedef struct {
    int k1;
    int k2;
    int left;
    int right;
} Tree;
Tree T1[MAX];
typedef struct {
    Tree *Data;
    int Top;
    int MaxSize;
}*Stack;
Stack CreateStack(int size) {
    Stack S=(Stack)malloc(sizeof(Stack));
    S->Data=(Tree*)malloc(sizeof(Tree)*size);
    S->MaxSize=size;
    S->Top=-1;
    return S;
}
bool IsEmpty(Stack S) {
    if(S->Top==-1)
        return true;
    return false;
}
void Push(Stack S,Tree x) {
    S->Data[++(S->Top)]=x;
}
Tree Pop(Stack S) {
    return S->Data[(S->Top)--];
}
int CreateTree(Tree T[]) {//建二叉树
    int n;
    scanf("%d",&n);
    int check[n];
    memset(check,0,sizeof(check));
    int i,root=-1;
    for(i=0; i<n; i++) {
        scanf("%d %d %d %d",&T[i].k1,&T[i].k2,&T[i].left,&T[i].right);
        check[T[i].left]=1;
        check[T[i].right]=1;
    }
    for(i=0; i<n; i++) {//找根结点
        if(!check[i]) {
            root=i;
            break;
        }
    }
    return root;
}
int max=INF_MIN;
int JudgeBiSearchTree(Tree T[],int r1,Stack S) {//判断是否二叉排序树
    int p=r1;
    while(!IsEmpty(S)||p!=-1) {
        while(p!=-1) {
            Push(S,T[p]);
            p=T[p].left;
        }
        Tree tmp=Pop(S);
        if(tmp.k1>max)
            max=tmp.k1;
        else
            return false;
        p=tmp.right;
    }
    return true;
}
int Judge(int r1,Tree T[]) {//判断是否堆排序
    if(r1==-1)
        return 1;
    if(T[r1].left==-1&&T[r1].right==-1)
        return 1;
    if((T[r1].left!=-1&&T[r1].right==-1)) {
        if(T[r1].k2<T[T[r1].left].k2)
            return Judge(T[r1].left,T);
        return 0;
    }
    if((T[r1].left==-1&&T[r1].right!=-1)) {
        if(T[r1].k2<T[T[r1].right].k2)
            return Judge(T[r1].right,T);
        return 0;
    }
    if((T[r1].left!=-1&&T[r1].right!=-1)) {
        if(T[r1].k2<T[T[r1].left].k2&&T[r1].k2<T[T[r1].right].k2)
            return Judge(T[r1].left,T)&&Judge(T[r1].right,T);
        return 0;
    }

}
int main() {
    int r1=CreateTree(T1);
    Stack S=CreateStack(MAX);
    if(JudgeBiSearchTree(T1,r1,S)) {
        if(Judge(r1,T1))
            printf("YES");
        else
            printf("NO");
    } else
        printf("NO");

}

 

posted @ 2020-03-10 19:46  跃鱼  阅读(328)  评论(0编辑  收藏  举报