二叉排序树查找最小值最大值操作(PTA)两种实现

本题要求实现二叉排序树的两个基本操作。
函数接口定义:

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;
}
  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值