Loading

<数据结构>BinarySearchTree的基本操作总结

ADT

结构声明

#include<stdio.h>
#include<stdlib.h>
#define ElementType int
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
struct TreeNode
{
    ElementType Element;
    SearchTree Left;
    SearchTree Right;
};

核心操作集

Position Find(int X, SearchTree T);
SearchTree Insert(int X, SearchTree T);
SearchTree Delete(int X, SearchTree T);

void PreOrderTraversal(SearchTree BT);
void InOrderTraversal(SearchTree BT);
void PostOrderTraversal(SearchTree BT);
void LevelOrderTraversal(SearchTree BT);

各操作实现

说明:SearchTree是递归定义,故操作多以递归实现,不再尝试转换为非递归实现

Find(),Insert(),Delete()

Position Find(int X, SearchTree T)
{
    if(T == NULL)
        return NULL;
    if(X < T->Element)
        return Find(X, T->Left);
    else
    if(X > T->Element)
        return Find(X, T->Right);
    else
        return T;
}
SearchTree Insert(int X, SearchTree T)
{
    if(T == NULL)
    {
        /*creat and return a one-node tree*/
        T = (SearchTree)malloc(sizeof(struct TreeNode));
        T->Element = X;
        T->Left = T->Right = NULL;
    }
    else
    if(X < T->Element)
        T->Left = Insert(X, T->Left);

    else
    if(X > T->Element)
        T->Right = Insert(X, T->Right);
    return T;
}
SearchTree Delete(int X, SearchTree T)
{
    Position TmpCell;

    if(T == NULL)
        printf("Element not found");
    else
    if(X < T->Element) /*Go Left*/
        T->Left = Delete(X, T->Left);
    else
    if(X > T->Element) /*Go Right*/
        T->Right = Delete(X, T->Right);
    else
    if(T->Left && T->Right) /*Two children*/
    {
        TmpCell = FindMax(T->Right);
        T->Element = TmpCell->Element;
        T->Right = Delete(T->Element, T->Right);
    }
    else /*One or Zero Children*/
    {
        TmpCell = T;
        if(T->Left == NULL)
            T = T->Right;
        if(T->Right == NULL)
            T = T->Left;
        free(TmpCell);
    }
    return T;
}

Traverse():前中后、层

void PreOrderTraverse(BinaryTree BT)
{
    if(BT)
    {
        printf("%d", BT->Element);
        PreOrderTraversal(BT->Left);
        PreOrderTraversal(BT->Right);
    }
}

InOrderTraverse()以及PostOrderTraverse()只需改变'printf()'位置即可'

void LevelOrderTraversal(BinaryTree BT)
{
    /*手法类似于BFS*/
    queue<BinaryTree> Q;
    BinaryTree T;
    if(!BT) return;
    Q.push(BT);
    while(!Q.empty())
    {
        T = Q.front();
        printf("%d ",T->Element);
        Q.pop();
        if(T->Left)  Q.push(T->Left);
        if(T->Right) Q.push(T->Right);
    }
}
posted @ 2021-11-22 23:49  咪啪魔女  阅读(46)  评论(0编辑  收藏  举报