注:笔记中的代码主要来自PTA算法练习通关的代码
二叉搜索树又名二叉排序树
操作集
BinTree Insert( BinTree BST, ElementType X );
BinTree Delete( BinTree BST, ElementType X );
Position Find( BinTree BST, ElementType X );
Position FindMin( BinTree BST );
Position FindMax( BinTree BST );
树结点结构
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
操作集实现
BinTree Insert( BinTree BST, ElementType X ) {
if (BST == NULL) { // 叶结点,插入
BST = (BinTree)malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = NULL;
BST->Right = NULL;
} else if (X < BST->Data) { // 左子树
BST->Left = Insert(BST->Left, X);
} else if (X > BST->Data) { // 右子树
BST->Right = Insert(BST->Right, X);
}
return BST;
}
BinTree Delete( BinTree BST, ElementType X ) {
BinTree tmp;
if (BST == NULL)
printf("Not Found\n");
else {
if (X < BST->Data)
BST->Left = Delete(BST->Left, X);
else if (X > BST->Data)
BST->Right = Delete(BST->Right, X);
else { // 找到了删除位置,BST
if (BST->Left && BST->Right) { // 如果存在左右子树
tmp = FindMin(BST->Right); // 取BST结点的直接后继
BST->Data = tmp->Data; // 直接后继代替删除结点
BST->Right = Delete(BST->Right, tmp->Data); // 删除原来的直接后继
} else { // 如果只有左子树或右子树,让其根结点代替删除结点的位置即可
tmp = BST;
if (BST->Left == NULL)
BST = BST->Right;
else if (BST->Right == NULL)
BST = BST->Left;
free(tmp);
}
}
}
return BST;
}
Position Find( BinTree BST, ElementType X ) {
if (!BST)
return NULL;
if (BST->Data == X)
return BST;
else if (X < BST->Data)
return Find(BST->Left, X);
else if (X > BST->Data)
return Find(BST->Right, X);
}
Position FindMin( BinTree BST ) {
if (BST)
while (BST->Left)
BST = BST->Left;
return BST;
}
Position FindMax( BinTree BST ) {
if (BST)
while (BST->Right)
BST = BST->Right;
return BST;
}