The principle and realization of binary sort tree of data structure

      Binary Sort Tree (Binary Sort Tree) is also called binary search tree.

nature:

      If its left subtree is not empty, the values ​​of all nodes on the left subtree are less than the value of the root node;

      If its right subtree is not empty, the values ​​of all nodes on the right subtree are greater than the value of the root node;

      Its left and right subtrees are also binary sort trees respectively;

The definition of the node structure of the binary linked list of the binary tree:

typedef struct BiTNode               //节点结构
{
    int data;                        //数据点
    struct BiNode *lchild,*rchild;   //左右孩子指针
}BiTNode,*BiTree;

Implementation of the search algorithm of the binary sort tree:

/**
 * 递归查找二叉排序树T中是否存在key
 * 指针f指向T的双亲,其初始化调用值为NULL
 * 若查找成功,则指针p指向该数据元素节点,并返回TRUE
 * 否则指针p指向查找路径上访问的最后一个节点并返回FALSE
*/
Status SearchBST(BiTree T,int key, BiTree f,BiTree *p)
{
    if(!T)              //查找失败
    {
        *p = f;
        return FALSE;
    }
    else if (key == T->data)     //查找成功
    {
        *p = T;
        return TRUE;
    }
    else if(key < T->data)
        return SearchBST(T->lchild, key, T, p);         //在左子树继续查找
    else 
        return SearchBST(T->rchild, key, T, p);       //在右子树继续查找
}

Binary sort tree insertion operation:

/**
 * 二叉排序树的插入操作
 * 当二叉排序树T中中不存在关键字等于Key的数据元素时
 * 插入key并返回true,否则返回false
*/

Status InsertBST(BiTree *T, int key)
{
    BiTree p,s;
    if(!SearchBST(*T, key,NULL, & p))     //查找不成功
    {
        s = (BiTree)malloc(sizeof(BiTNode));
        s->data = key;
        s->lchild = s->rchild = NULL;
        if(!p)
            *T = s;                      //插入s为新的根节点
        else if(key < p->data)
            p->lchild = s;              //插入s为左孩子
        else
            p->rchild = s;              //插入s为右孩子 
        return TRUE;
    }
    else
    {
        return FALSE;               //树中已经有关键字相同的节点,不再插入
    }
    
}

 

Guess you like

Origin blog.csdn.net/songjun007/article/details/108542895