本题要求实现函数,判断给定二叉树是否二叉搜索树。
函数接口定义:
bool IsBST ( BinTree T );
其中BinTree
结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
函数IsBST
须判断给定的T
是否二叉搜索树,即满足如下定义的二叉树:
定义:一个二叉搜索树是一棵二叉树,它可以为空。如果不为空,它将满足以下性质:
- 非空左子树的所有键值小于其根结点的键值。
- 非空右子树的所有键值大于其根结点的键值。
- 左、右子树都是二叉搜索树。
如果T
是二叉搜索树,则函数返回true,否则返回false。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef enum { false, true } bool;
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree BuildTree(); /* 由裁判实现,细节不表 */
bool IsBST ( BinTree T );
int main()
{
BinTree T;
T = BuildTree();
if ( IsBST(T) ) printf("Yes\n");
else printf("No\n");
return 0;
}
/* 你的代码将被嵌在这里 */
/*BinTree BuildTree(){ //pc端
BinTree BT;
char c;
scanf("%c",&c);
if(c=='#') BT = NULL;
else{
BT=(BinTree)malloc(sizeof(struct TNode));
BT->Data = c;
BT->Left = BuildTree();
BT->Right = BuildTree();
}
return BT;
} */
bool IsBST ( BinTree T )
{
if(!T) return true;
if(!T->Left&&!T->Right) return true;
BinTree TR = T->Right;
if(TR){
while(TR->Left) TR = TR->Left;
}
BinTree TL=T->Left;
if(TL){
while(TL->Right) TL = TL->Right;
}
if(TL->Data<T->Data&&TR->Data>T->Data) return true;
else return false;
}