判断二叉树是否为二叉排序树
输入的原始数组为,a[7]={49,99,65,97,76,13,27},可以先在草稿纸上模拟,再看程序
实现代码:
#include <stdio.h>
#include <stdlib.h>
int predit=-1000;//保存当前节点中序前驱值,开始假设为最小值
typedef struct BTNode{
int data;
struct BTNode *lchild,*rchild;
}BTNode;
//创建二叉排序树
int BSTInsert(BTNode *&bt,int x){
if(bt==NULL){
bt=(BTNode*)malloc(sizeof(BTNode));
bt->data=x;
bt->lchild=bt->rchild=NULL;
}else if(bt->data==x){
return 0;
}else if(bt->data>x){
return BSTInsert(bt->lchild,x);
}else{
return BSTInsert(bt->rchild,x);
}
}
//创建二叉树
int CreateBTree(BTNode *&tree,int x){
if(tree==NULL){
tree=(BTNode *)malloc(sizeof(BTNode));
tree->data=x;
tree->rchild=tree->lchild=NULL;
}else {
CreateBTree(tree->lchild,x);
CreateBTree(tree->rchild,x);
}
}
//判断二叉树是否为二叉排序树
int JudgeBST(BTNode *bt){
int b1,b2;
if(bt==NULL){
return 1;
}else{
b1=JudgeBST(bt->lchild);
if(b1=0||predit>bt->data){
return 0;
}
predit=bt->data;
b2=JudgeBST(bt->rchild);
return b2;
}
}
int main(int argc, char *argv[])
{
struct BTNode *bt1=NULL,*bt2=NULL;
int i,a[7]={49,99,65,97,76,13,27};
for(i=0;i<7;++i){
BSTInsert(bt1,a[i]);
CreateBTree(bt2,a[i]);
}
printf("%d\n",JudgeBST(bt1));//输出1表示是二叉排序树
printf("%d\n",JudgeBST(bt2));//输出0表示不是
return 0;
}
输出结果:
1
0
请按任意键继续. . .