二叉樹的建立
#include <iostream>
#include <vector>
using namespace std;
typedef struct Bin_tree BinTree;
struct Bin_tree
{
int value;
BinTree* right;
BinTree* left;
};
爲了使二叉樹可在類內建立,可以在構造函數中聲明變量
BinTree* root;
然後在成員函數中初始化
root =NULL;
接着調用InsertFromArray()
void InsertFromArray(BinTree*& root,int* array,int start,int end)
{
if(start >end)
return ;
root = new BinTree;
root->left = NULL;
root->right = NULL;
int mid = start+(end-start)/2;
root->value = array[mid];
InsertFromArray(root->left,array,start,mid-1);
InsertFromArray(root->right,array,mid+1,end);
}
/*
遞歸 中序遍歷二叉樹
*/
void Inorder(BinTree* root)
{
if(root == NULL)
return ;
Inorder(root->left);
cout<<root->value<<endl;
Inorder(root->right);
}
int main()
{
int array[]={1,2,3,4,5,6,7,8,9};
BinTree* root =NULL;
InsertFromArray(root,array,0,8);
Inorder(root);
system("pause");
return 0;
}
二叉樹的遍歷搜尋
在類中定義變量 vector<..> FilteredVectorList, 用來存儲符合條件的數據
void MatchWithDistMaps::VisitandFilter(BinTree *bTree,float key,float tolerance)
//這個是先序遍歷,先根,左子樹,右子樹
{
if(bTree != NULL)
{
float mindist=(float)VectorMinMaxAlphaDist[bTree->idx].mindist;
if (abs(mindist-key)<tolerance)
{
FilteredVectorList.push_back(bTree->idx);
}
if(key<(float)VectorMinMaxAlphaDist[bTree->idx].mindist+tolerance)
{
VisitandFilter(bTree->left,key,tolerance);
}
if(key>(float)VectorMinMaxAlphaDist[bTree->idx].mindist-tolerance)
{
VisitandFilter(bTree->right,key,tolerance);
}
}
}
對一個無序的 vector<..self define structure>, 根據鍵值,使用二叉樹實現快速搜索的思路:
首先建立一個vector< idx > {0,1,2,3……}
和vector<..self define structure>一同,根據前者的鍵值進行排序
對排序之後的 vector< idx > 建立二叉樹,這個二叉樹的意義在於記錄了前者的大小關係,接下來對二叉樹實施條件遍歷,就可以快速查找到相應的數據
冒泡排序
void print(float* pData,int* idx, int count){
for (int i = 0; i< count; i++) {
cout << pData[i] << ” “;
}
cout << endl;
for (int i = 0; i < count; i++) {
cout << idx[i] << " ";
}
cout << endl;
}
void BubbleSort(float* pData,int* idx, int count)
{
int temp;
int tempidx;
for (int i = 1; i < count; i++)
{
for (int j = count - 1; j >= i; j–)
{
if (pData[j] < pData[j - 1])
{
temp = pData[j - 1];
pData[j - 1] = pData[j];
pData[j] = temp;
tempidx=idx[j-1];
idx[j-1]=idx[j];
idx[j]=tempidx;
}
}
cout << "The "<< i <<" round:" << endl;
print(pData,idx, count);
cout << "----------------------------" << endl;
}
}
int main()
{
float data[] = {10, 8, 9, 7, 4, 5};
int idx[]={0,1,2,3,4,5};
BubbleSort(data,idx, 6);
cout << "The sort result:" << endl;
print(data,idx, 6);
}