一棵排序二叉树,令 f=(最大值+最小值)/2,设计一个算法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。

#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);  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值