是否二叉搜索樹

習題4.3 是否二叉搜索樹   (25分)

本題要求實現函數,判斷給定二叉樹是否二叉搜索樹。

函數接口定義:

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;
}
/* 你的代碼將被嵌在這裏 */

輸入樣例1:如下圖

輸出樣例1:

Yes

輸入樣例2:如下圖

輸出樣例2:

No

#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);
ElementType maxValue(BinTree T);
ElementType minValue(BinTree T);


int main(){
	BinTree T;

	T = BuildTree();
	if(IsBST(T))
		printf("Yes\n");
	else
		printf("No\n");

	return 0;
}


bool IsBST(BinTree T) {  
	if (T==NULL) 
		return true;  
    if (T->Left!=NULL && maxValue(T->Left) > T->Data)  
		return false;  
    if (T->Right!=NULL && minValue(T->Right) <= T->Data)  
		return false;  
     // check that the subtrees are ok  
    return (IsBST(T->Left) && IsBST(T->Right));  
}  

ElementType maxValue(BinTree T){
	int max;
	BinTree p;

	p=T->Left;
	max = T->Data;
	while(p){
		if(max<p->Data){
			printf("max = %d, p->Data = %d\n", max, p->Data);	
			max=p->Data;
		}
		p=p->Left;
	}
	return max;
}

ElementType minValue(BinTree T){
	int min;
	BinTree p;

	p=T->Right;
	min = T->Data;
	while(p){
		if(min>p->Data){
			printf("min = %d, p->Data = %d\n", min, p->Data);
			min=p->Data;
		}
		p=p->Right;
	}
	return min;
}

/*
 4 3 1 -1 2 -1 -1 -1 5 -1 7 6 -1 -1 8 -1 -1
 4
 */
/*
 4 5 1 -1 -1 -1 3 6 -1 -1 7 -1 -1
 3
 */

BinTree BuildTree(){
    BinTree T = NULL;
    int val;
    
    scanf("%d", &val);
    if(-1 == val){
        return T;
    }
    T = (BinTree)malloc(sizeof(struct TNode));
    T->Data = val;
    T->Left = BuildTree();
    T->Right = BuildTree();
    return T;
}


發佈了94 篇原創文章 · 獲贊 80 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章