二叉树查找一直以来是效率较高的查找方式,现在我们从基础开始,假如给定一个数组,如何根据数组建立二叉树 ?
转载请注明出处: 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<