二叉搜索树
二叉搜索树的查找-递归实现
Position Find( ElementType X, BinTree BST ) {
if ( !BST )
return NULL;
if ( X > BST->Data )
return Find(X, BST->Right);
else if ( X < BST->Data )
return Find(X, BST->Left);
else
return BST;
}
二叉搜索树的查找-非递归实现
Position IterFind( ElementType X, BinTree BST ) {
while ( BST ) {
if ( X > BST->Data )
BST = BST->Right;
else if ( X < BST->Data )
BST = BST->Left;
else
return BST;
}
return NULL;
}
二叉搜索树查找最小值
Position FindMin( BinTree BST ) {
if ( !BST )
return NULL;
else if ( !BST->Left )
return BST;
else
return FindMin(BST->Left);
}
二叉搜索树查找最大值
Position FindMax( BinTree BST ) {
if ( BST )
while ( BST->Right )
BST = BST->Right;
return BST;
}
二叉搜索树插入操作
BinTree Insert ( ElementType X, BinTree BST) {
if ( !BST ) {
BST = (BinTree)malloc(sizeof(struct TreeNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
} else if ( X < BST->Data ) {
BST->Left = Insert( X, BST->Left);
} else if (X > BST->Data ) {
BST->Right = Insert(X, BST->Right);
}
return BST;
}
二叉搜索树删除操作
BinTree Delete ( ElementType X, BinTree BST) {
Position Tmp;
if ( !BST )
printf("The binary search tree is empty.\n");
else if ( X < BST->Data )
BST->Left = Delete(X, BST->Left);
else if ( X > BST->Data )
BST->Right = Delete(X, BST->Right);
else if ( BST->Left && BST->Right ) {
Tmp = FindMin( BST->Right );
BST->Data = Tmp->Data;
BST->Right = Delete(BST->Data, BST->Right);
} else {
Tmp = BST;
if ( !BST->Left )
BST = BST->Right;
else if ( !BST->Right )
BST = BST->Left;
free(Tmp);
}
return BST;
}
参考自:
https://www.icourse163.org/learn/ZJU-93001#/learn/announce