6.2树型查找

一.BST

特征:进行中序排列为有序序列

1.结构体定义

typedef struct BSTNode
{
    int key;
    struct BSTNode *lchild, *rchild;
} BSTNode, *BSTree;

2.基本操作

1.查找

1.循环查找的实现

BSTNode *BST_Serch(BSTree T, int key)
{
    while (T != NULL && key != T->key)
    {
        if (key < T->key)
            T = T->lchild;
        else
            T = T->rchild;
    }
    return T;
}

2.递归查找的实现

BSTNode *BSTSearch(BSTree T, int key)
{
    if (T == NULL)
        return NULL;
    if (key == T->key)
        return T;
    else if (key < T->key)
        return BSTSearch(T->lchild, key);
    else
        return BSTSearch(T->rchild, key);
}

2.插入

递归实现二叉排序树的插入

int BST_Insert(BSTree &T, int k)
{
    if (T == NULL)
    {
        T = (BSTree)malloc(sizeof(BSTNode));
        T->key = k;
        T->lchild = T->rchild = NULL;
        return 1;
    }
    else if (key == T->key)//相同元素插入失败
            return 0;
    else if(k<T->key)
    return BST_Insert(T->lchild, k);
    else
        return BST_Insert(T->rchild,k);
}

非递归实现二叉排序树的插入(代码可能错误)

int BST_Insert(BSTree &T, int k)
{
   if (T == NULL)
    {
        T = (BSTree)malloc(sizeof(BSTNode));
        T->key = k;
        T->lchild = T->rchild = NULL;
        return 1;
    }
    while (key != T->key && T != NULL)
    {
        if (K < T->key)
            T = T->lchild;
        else
            T = T->rchild;
    }
}

3.BST构造

void Create_BST(BSTree &T, int str[], int n)
{
    T = NULL;
    int i = 0;
    while (i < 0)
    {
        BST_Insert(T, str[i]);
        i++;
    }
}

你可能感兴趣的:(Alogrithm,java,算法,数据结构)