给定数组,如何快速建立查找二叉树

二叉树查找一直以来是效率较高的查找方式,现在我们从基础开始,假如给定一个数组,如何根据数组建立二叉树 ?

转载请注明出处: http://blog.csdn.net/elfprincexu

现附上截图:

《给定数组,如何快速建立查找二叉树》《给定数组,如何快速建立查找二叉树》

简单的策略: 

1. 将数组从小到大进行排序, 这里使用std::sort 函数, 自定义mycomp 比较函数,从小到大进行排序。

2. 排序后的数组从小到大,查找二叉树应该是始终是左小右大的规律

3. 递归算法,每次去数组中间数作为parent, 将剩下的左右数组做递归 (递归终止条件为子数组长度<=0)。

模板:

由于数组中可能有int , double, float类型, 因此采用模板函数。

附上源码,亲测可Run…

#include <vector>
#include <Windows.h>
#include <algorithm>
using namespace std;
template <class T>
struct node {
    T data;
    struct node<T>* left;
    struct node<T>* right;
};
typedef node<int> IntNode;
typedef node<double> DoubleNode;
typedef node<float> FloatNode;
template<class T>
void buildTree( node<T>*& root, vector<T>& array, int begin,  int end)    // here we use a reference pointer root
{
    if (begin>end  ) return;     // ending condition
    int middle =(begin+end)/2;
    if (root == NULL)
    {
        root = new node<T>();         // create a new node, if not root, has its parent
        root->left = NULL;            // set null to left
        root->right = NULL;
        root->data =array[middle];
    }
    cout<< root->data << " ";
    Sleep(50);
    // recursively build left child and right child
    buildTree(root->left,array,begin,middle-1);
    buildTree(root->right,array,middle+1,end);
}
template <class T>
int mycmp(T a, T b)
{
    return a < b;
}
template <class T>
void travel(node<T>* root)
{
    if (root !=NULL )
    {
    travel(root->left);
    cout<< root->data <<" ";
    travel(root->right);
    }
}
int main()
{
    vector<int> array(100);
    for (unsigned int i=0 ;i< array.size() ; i++) {
        array[i] = i;
    }
    sort(array.begin(), array.end(),mycmp<int>);
    for (unsigned int i=0 ;i< array.size() ; i++) {
        cout<< array[i] << " ";
    }
    cout << endl;
    cout << "Building Tree..." <<endl;
    IntNode* root= NULL;
    buildTree(root, array, 0, array.size()-1);
    cout<<endl;
    cout<<"middle travel begins"<<endl;
    cout<< "root: " << root << " root->data: " << root->data << endl;
    travel(root);
    cout<< endl;
    return 0;
}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/elfprincexu/article/details/32344103
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞