Description
试编写程序,判别给定的二叉树是否为二叉排序树。设此二叉树以二叉链表作存储结构,且树中结点的关键字均不同。
Input
按先序输入二叉树各结点(结点值大于0),其中-1表示取消建立子树结点。
Output
若该二叉树为二叉排序树,则输出yes;否则,输出no。
-
Sample Input
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1
-
Sample Output
yes
#include<stdio.h>
#include<stdlib.h>
typedef struct BinNode
{
int data;
struct BinNode *lchild;
struct BinNode *rchild;
}BinNode,*BinTree;
void CreateBinTree(BinNode *tree)
{
int ch;
scanf("%d",&ch);
if(ch == -1)
{
tree = NULL;
}
else
{
tree = (BinTree)malloc(sizeof(BinNode));
tree->data = ch;
CreateBinTree(tree->lchild);
CreateBinTree(tree->rchild);
}
}
int judge(BinNode *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)
return 0;
else
return judge(t->lchild);
}
else if((t->rchild) && !(t->lchild))
{
if(t->rchild->data<t->data)
return 0;
else
return judge(t->rchild);
}
else
{
if((t->lchild->data>t->data) || (t->rchild->data<t->data))
return 0;
else
return ( judge(t->lchild) && judge(t->rchild) );
}
}
int main()
{
BinNode *T = NULL;
CreateBinTree(T);
int flag=judge(T);
if(flag)printf("yes\n");
else printf("no\n");
return 0;
}