是否二叉搜索树

来源:互联网 发布:淘宝设置不包邮地区 编辑:程序博客网 时间:2024/06/06 01:20

习题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");elseprintf("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;}


原创粉丝点击