BST中所有结点之和(设结点个数为n,且中序遍历为等差数列)

来源:互联网 发布:上海网络视听产业基地 编辑:程序博客网 时间:2024/05/22 01:37

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

#include <iostream>using namespace std;// BST的结点typedef struct node{int key;struct node *lChild, *rChild;}Node, *BST;// 在给定的BST插入element, 使之称为新的BSTbool 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); // 递归}// 建立BSTvoid 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;}