6-2 Whether or not a binary search tree (25 points)

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 BinTreestructure is defined as follows:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

The function IsBSTmust determine whether the given Tbinary 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 Tis 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);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324795861&siteId=291194637