其实,就是要求最小值和最大值之和, 程序如下:

 

#include <iostream>
using namespace std;

// BST的结点
typedef struct node
{
	int key;
	struct node *lChild, *rChild;
}Node, *BST;

// 在给定的BST插入element, 使之称为新的BST
bool BSTInsert(Node * &p, int element)
{
	if(NULL == p) // 空树
	{
		p = new Node;
		p->key = element;
		p->lChild = p->rChild = NULL;
		return true;
	}

	if(element == p->key) // BST中不能有相等的值
		return false;

	if(element < p->key)  // 递归
		return BSTInsert(p->lChild, element);

	return BSTInsert(p->rChild, element); // 递归
}

// 建立BST
void createBST(Node * &T, int a[], int n)
{
	T = NULL; 
	int i;
	for(i = 0; i < n; i++)
	{
		BSTInsert(T, a[i]);
	}
}

int minPlusMax(BST T)
{
	Node *p = T;
	while(NULL != T->lChild) // 一路向左狂奔
		T = T->lChild;
	
	while(NULL != p->rChild) // 一路向右狂奔
		p = p->rChild;
	
	return T->key + p->key;
}

int main()
{
	int a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8};
	int n = 10;

	BST T = NULL;

	// 并非所有的a[]都能构造出BST,所以,最好对createBST的返回值进行判断
	createBST(T, a, n);
	
	// minPlusMax(T) * n 必然为偶数,所以不同担心截断
	cout << minPlusMax(T) * n / 2 << endl;

	return 0;
}

 
 

 


本文转载:CSDN博客