Description
二叉排序树用二叉链表存储,结点结构为:lchild | key |rchild,其中key为int类型, 要求编写算法:
(1)输入n个关键字,建立二叉排序树;
(2)判断该二叉排序树树是不是平衡二叉树,是输出1,否则输出0。
Input
输入n
依次输入关键字,以空格分隔
Output
如果是不是平衡二叉树,输出1,否则输出0.
Sample Input
10 20 30
Sample Output
1
#include <stdio.h>
#include <stdlib.h>
typedef struct BTNode{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode,*BSTree;
BSTree InsertBST(BSTree T,BTNode *s){
if(T == NULL){
T = s;
}else{
if(s->key < T->key){
T->lchild = InsertBST(T->lchild,s);
}else if(s->key > T->key){
T->rchild = InsertBST(T->rchild,s);
}
}
return T;
}
int height(BSTree T) {
if (!T) return 0;
int left = height(T->lchild);
int right = height(T->rchild);
int max = (left > right)?left:right;
return max+1;
}
int isAVL(BSTree T) {
if (!T) return 1;
if (abs(height(T->lchild)-height(T->rchild)) >1) return 0;
return isAVL(T->lchild) && isAVL(T->rchild);
}
int main()
{
BSTree T = (BSTree)malloc(sizeof(BSTree));
int n;
scanf("%d",&n);
int val;
scanf("%d",&val);
T->key = val;
T->lchild = NULL;
T->rchild = NULL;
for(int i = 0; i < n -1; i++){
int val;
scanf("%d",&val);
BTNode *s = (BTNode*)malloc(sizeof(BTNode));
s->key = val;
s->lchild = NULL;
s->rchild = NULL;
InsertBST(T,s);
}
if(isAVL(T)){
printf("0");
}else{
printf("1");
}
return 0;
}