本题要求实现二叉排序树的两个基本操作。
函数接口定义:
BSTree FindMin( BSTree T);
BSTree FindMax( BSTree T);
函数FindMin返回二叉排序树T中最小元素结点的指针;
函数FindMax返回二叉排序树T中最大元素结点的指针。
其中BSTree结构定义如下:
typedef int ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
BSTree CreateBST(); /* 二叉排序树创建,由裁判实现,细节不表 */
BSTree FindMin( BSTree T);
BSTree FindMax( BSTree T);
void Inorder(BSTree T);/* 中序遍历,由裁判实现,细节不表 */
int main()
{
BSTree T,MinP, MaxP;
ElemType n,e;
T = CreateBST();
printf("Inorder:"); Inorder(T); printf("\n");
MinP = FindMin(T);
MaxP = FindMax(T);
if(MinP) printf("%d is the smallest key\n",MinP->data);
if(MaxP) printf("%d is the largest key\n",MaxP->data);
return 0;
}
/* 你的代码将被嵌在这里 */
还是我自己的做法,用了递归做的:
BSTree FindMin( BSTree T)
{
if(!T) return NULL;
if(T)
{
if(T->lchild) return FindMin(T->lchild);
return T;
}
return NULL;
}
BSTree FindMax( BSTree T)
{
if(!T) return NULL;
if(T)
{
if(T->rchild) return FindMax(T->rchild);
return T;
}
}
另一种是用循环:
BSTree FindMin(BSTree T)
{
if (!T) return NULL;
BSTree p = T;
while (p&&p->lchild) p = p->lchild;
return p;
}
BSTree FindMax(BSTree T)
{
if (!T) return NULL;
BSTree p = T;
while (p&&p->rchild) p = p->rchild;
return p;
}