This question requires implementing a function to determine whether a given binary tree is a binary search tree.
Function interface definition:
bool IsBST ( BinTree T );
where the BinTree
structure is defined as follows:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
The function IsBST
must determine whether the given T
binary search tree is a binary tree that satisfies the following definition:
Definition: A binary search tree is a binary tree, which can be empty. If not empty, it will satisfy the following properties:
- All keys of the non-empty left subtree are less than the keys of its root node.
- All keys of the non-empty right subtree are greater than the keys of its root node.
- The left and right subtrees are both binary search trees.
The function returns true if it T
is a binary search tree, false otherwise.
Example of the referee test procedure:
#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;
}
/* 你的代码将被嵌在这里 */
Input example 1: as shown below
Sample output 1:
Yes
Input example 2: as shown below
Sample output 2:
No
code;
bool IsBST ( BinTree T )
{
BinTree p;
if(!T)
return true;
if(!T->Left&&!T->Right)
return true;
p=T->Left;
if(p)
{
while(p->Right)//左子树的最大值在右下角
p=p->Right;
if(p->Data>T->Data)
return false;
}
p=T->Right;
if(p)
{
while(p->Left)//右子树的最小值在左下角
p=p->Left;
if(p->Data<T->Data)
return false;
}
return IsBST(T->Left)&&IsBST(T->Right);
}