一颗二叉查找树的简单实现

来源:互联网 发布:java遍历json 编辑:程序博客网 时间:2024/05/22 17:46

       第一次实现的二叉查找树,在别的大牛的博客学习了很久很久。发现由于其使用的技巧较多,不适用与新手模仿,所以自己实践写出了一个有局限性,功能专一化,不完整的二叉查找树。

       使用了c++中的类来定义节点,并没有定义专门的树类,以减小代码复杂性。

class BSTNode{    private:        int key;                    BSTNode *left;            BSTNode *right;       public:        BSTNode(int value, BSTNode *l, BSTNode *r):            key(value),left(l),right(r) {}        BSTNode* Insert(BSTNode* tree,int k);        void preOrder(BSTNode* tree,int depth);};
    实现的操作只有两个,但已经能测试出树的主要功能了。

    1.插入(Insert)

BSTNode* BSTNode::Insert(BSTNode* tree,int k){    if(tree== NULL){        tree=new BSTNode(k,NULL,NULL,NULL);    }    else if(k<tree->key)        tree->left=Insert(tree->left,k);    else        tree->right=Insert(tree->right,k);    return tree;}
    这段插入使用了递归实现,在实现函数时需要给定实参指针,不是很方便。但胜在简洁。

    2.先序输出(preOrder)

void BSTNode::preOrder(BSTNode* tree,int depth){    if(tree!=NULL)    {        for(int i=0;i<depth;i++)            cout<<"  ";        cout<<tree->key <<endl;        preOrder(tree->left,depth+1);        preOrder(tree->right,depth+1);    }    return;}
    采取了输出文件式的格式,按树的深度缩进空格,可直观看出书的实现情况。

    具体的程序。

int arr[]={1,7,9,41,23,4,3,5,6};int main(){    BSTNode *root=NULL;    for(int i=0;i<9;i++){        cout<<arr[i]<<"  ";        root=root->Insert(root,arr[i]);    }    cout<<"\n==前序遍历:"<<endl;;    root->preOrder(root,0);    return 0;}
    定义好了一数组。将其数据存入BSTNode对象的组成的二叉查找树结构中。并且按先序输出出来。

    代码的优点在于简单,适合像我一样的新手自主摸索参考。其余功能可逐步添加。以达到掌握的目的。


0 0