一棵排序二叉树,令 f=(最大值+最小值)/2,设计一个算法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。
来源:互联网 发布:死或生5mac 编辑:程序博客网 时间:2024/06/06 07:47
#include "stdafx.h" #include <iostream> #include <cassert> #include <iterator> using namespace std; struct Node { int elememt; Node *pLeft; Node *pRight; Node(int ele, Node *left = NULL, Node *right = NULL) :elememt(ele), pLeft(left), pRight(right){} }; //插入元素 void InsertNode(Node *&root, int ele) { if(NULL == root) root = new Node(ele); else if (root->elememt > ele) InsertNode(root->pLeft, ele); else if (root->elememt < ele) InsertNode(root->pRight, ele); } //创建二叉查找树 void CreateTree(Node *&root, int arr[], int len) { for (int i = 0; i < len; i++) InsertNode(root, arr[i]); } //中序输出树 void MiddlePrint(Node *root) { if (NULL == root) return; MiddlePrint(root->pLeft); cout<<root->elememt<<" "; MiddlePrint(root->pRight); } //获得最大值 int GetMaxValue(Node *root) { assert(root != NULL); while (root->pRight != NULL) root = root->pRight; return root->elememt; } //获得最小值 int GetMinValue(Node *root) { assert(NULL != root); while (root->pLeft != NULL) root = root->pLeft; return root->elememt; } //查找指定的结点 Node *FindNode(Node *root, int target) { assert(NULL != root); int diff = INT_MAX; Node *p = NULL; while (root != NULL) { if (root->elememt > target) { if (root->elememt - target < diff) { diff = root->elememt - target; p = root; } root = root->pLeft; } else if (root->elememt < target) { root = root->pRight; } } return p; } int main() { int arr[] = {20, 8, 22, 4, 12, 10, 14}; int len = sizeof(arr) / sizeof(int); Node *root = NULL; CreateTree(root, arr, len); MiddlePrint(root); printf("/n"); int minValue = GetMinValue(root); int maxValue = GetMaxValue(root); Node *node = FindNode(root, (minValue + maxValue) / 2); assert(NULL != node); printf("%d/n", node->elememt); }