每日编程24之BST

来源:互联网 发布:mac os x最新系统下载 编辑:程序博客网 时间:2024/06/05 22:37

BST,二叉查找树,又叫排序二叉树,指一种树,对于每一个树节点,其左子树的值<root值<右子树的值,这一特性主要用来优化查找操作,在树较为平衡的情况下,查找的复杂度为O(H),或O(logN)。。。但一般在某一段时间插入的数据的局部集中性很强,很有可能会破坏树的平衡性,使得查找的复杂度增加,因此明天讨论二叉查找树的变形——平衡二叉树,红黑树


关键的操作

(1)根据元素序列,初始化,构建一颗二叉查找树,基于插入操作

(2)对于一颗二叉查找树,插入一个元素,并保持二叉查找树的特征

(3)查找操作,删除操作


int insert_bst(BTree bst,int e)
{
        struct node *pt = bst;
        while(pt)
        {
                if(e < pt->data)        pt = pt->left;
                else    pt = pt->right;
        }
        pt = (struct node *)malloc(sizeof(struct node));
        pt->data = e;
}




int init_bst(BTree &bst)
{
        int ch;
        while((ch=getchar())!='x')
        {
                if(!bst)
                {
                        bst = (struct node*)malloc(sizeof(struct node));
                        bst->data = ch-'0';
                        break;
                }
                insert_bst(bst,ch-'0');
        }
}


struct node* search_bst(BTree bst,int e)
{
        while(bst)
        {
                if(e==bst->data)        return bst;
                if(e > bst->data)       bst=bst->right;
                else    bst=bst->left;
        }
        printf("no element %d found!\n",e);
        return NULL;
}




OVER!!!




原创粉丝点击