二叉树的建立,遍历查找

二叉树的建立

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

}

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