#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild, *rchild;
}Bitree;
Bitree *B[100];
Bitree *CreateBiTree()
{
int num, i, n;
Bitree *t, *s;
t = NULL;
printf("建立二叉树(-1表示为虚结点,-2表示输入结束):/n");
num = 0;
scanf("%d", &n);
while (n != -2)
{
s = (Bitree *)malloc(sizeof(Bitree));
s->data = n;
s->lchild = s->rchild = NULL;
num++;
if (!t)
t = s;
B[num] = s;
scanf("%d", &n);
}
for (i = 1; i <= num; i++)
{
if (B[i]->data != 1)
{
if (2 * i <= num && B[2 * i]->data != -1)
B[i]->lchild = B[2 * i];
if (2 * i + 1 <= num && B[2 * i + 1]->data != -1)
B[i]->rchild = B[2 * i + 1];
}
}
return t;
}
int IsSearchTree(const Bitree *t) //递归遍历二叉树是否为二叉排序树
{
if (!t) //空二叉树情况
return 1;
else if (!(t->lchild) && !(t->rchild)) //左右子树都无情况
return 1;
else if ((t->lchild) && !(t->rchild)) //只有左子树情况
{
if (t->lchild->data > t->data) //左子树的值比其父节点大,返回0不是二叉排序树
return 0;
else
return IsSearchTree(t->lchild); //递归往下找
}
else if ((t->rchild) && !(t->lchild)) //只有右子树情况
{
if (t->rchild->data < t->data) //右子树的值比其父节点值小,返回0不是二叉排序树
return 0;
else
return IsSearchTree(t->rchild); //递归往下找
}
else //左右子树全有情况
{
if ((t->lchild->data > t->data) || (t->rchild->data < t->data)) //左子树的值比其父节点大或者右子树的值比其父节点值小,返回0不是二叉排序树
return 0;
else
return (IsSearchTree(t->lchild) && IsSearchTree(t->rchild)); //递归往下找
}
}
int main(void)
{
int flag = 0;
Bitree *tree;
tree = CreateBiTree();
flag = IsSearchTree(tree);
if (flag)
printf("这棵树是二叉排序树!/n");
else
printf("这棵树不是二叉排序树!/n");
system("pause");
return 0;
}
建立二叉树(-1表示为虚结点,-2表示输入结束):/n
8 5 10 3 6 9 11 -2
这棵树是二叉排序树!/n请按任意键继续. . .
建立二叉树(-1表示为虚结点,-2表示输入结束):/n
12 23 2 21 12 12 1 123 32 1 12 21
-2
这棵树不是二叉排序树!/n请按任意键继续. . .