Whether binary search tree PTA

This problem required to achieve a function to determine whether a given binary tree binary search tree.

Function interface definition:

bool IsBST ( BinTree T );

Wherein BinTree structure is defined as follows:

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

IsBST shall function determines whether a given binary search tree T, i.e., satisfies the following binary definitions:

Definition: A binary search tree is a binary tree, it can be empty. If not empty, it will satisfy the following properties:

All key non-empty left subtree is less than its root keys.
All key non-empty right subtree is greater than its root keys.
Left and right sub-trees are binary search trees.
If T is a binary search tree, the function returns true, otherwise false.

Referee test program Example:

#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 Sample 1: below

Here Insert Picture Description

Output Sample 1:

Yes

Input Sample 2: below

Here Insert Picture Description

Output Sample 2:

No

Code:

//方法:根据二叉树搜索树的性质,当左子树中的最大值小于根结点且右子树的最小值大于根结点时,
//可确定一棵二叉搜索树
bool IsBST ( BinTree T )
{
	BinTree L,R;
	if(!T)return true;
	if(!T->Right && !T->Left)return true;
	L=T->Left; //注意:这里的赋值必须是在确定该树存在右子数和右子数之才能定义
	R=T->Right;
	if(L)//如果存在左子树
	{
		while(L->Right)L=L->Right;
		if(L->Data>T->Data)return false;
	}
	if(R)
	{
		while(R->Left)R=R->Left;
		if(R->Data<T->Data)return false;
	}
	return true;
}

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_44256227/article/details/89981211
Recommended