SearchTree MakeEmpty( SearchTree T ); Position Find( ElementType X, SearchTree T ); Position FindMin( SearchTree T ); Position FindMax( SearchTree T ); SearchTree Insert( ElementType X, SearchTree T ); SearchTree Delete( ElementType X, SearchTree T ); ElementType Retrieve( Position P );
// 寻找节点 if (T == NULL) Error("Element not found"); elseif (X < T->Element) /* Go left */ T->Left = Delete(X, T->Left); elseif (X > T->Element) /* Go right */ T->Right = Delete(X, T->Right); else/* Found element to be deleted 找到了该删除的节点 */ { if (T->Left && T->Right) /* Two children 有两个孩子 */ { /* Replace with smallest in right subtree 用右子树中最小的节点进行替换 */ TmpCell = FindMin(T->Right); // 找出右子树中最小的节点 T->Element = TmpCell->Element; // 替换 T->Right = Delete(T->Element, T->Right); // 删除刚刚的那个在右子树中最小的节点 } else/* One or zero children 有 1 个或者 0 个孩子 */ { TmpCell = T; if (T->Left == NULL) /* Also handles 0 children */ T = T->Right; // 如果左子树为空,那么将 T 更新为右子树,下同 elseif (T->Right == NULL) T = T->Left; free(TmpCell); // 释放原来的 T 节点 } }
return T; }
/* END */
// 取出 Position P 中的元素 ElementType Retrieve(Position P) { return P->Element; }
intmain( ) { SearchTree T; Position P; int i; int j = 0;
T = MakeEmpty( NULL ); // 创建一棵空树 for( i = 0; i < 50; i++, j = ( j + 7 ) % 50 ) // 将 50 个数插入树中 T = Insert( j, T ); for( i = 0; i < 50; i++ ) if( ( P = Find( i, T ) ) == NULL || Retrieve( P ) != i ) // 测试查找函数 printf( "Error at %d\n", i );
for( i = 0; i < 50; i += 2 ) T = Delete( i, T ); // 以 1 为步长,作删除操作
// 测试删除操作是否成功 for( i = 1; i < 50; i += 2 ) if( ( P = Find( i, T ) ) == NULL || Retrieve( P ) != i ) printf( "Error at %d\n", i ); for( i = 0; i < 50; i += 2 ) if( ( P = Find( i, T ) ) != NULL ) printf( "Error at %d\n", i );
// 打印最大数和最小数 printf( "Min is %d, Max is %d\n", Retrieve( FindMin( T ) ), Retrieve( FindMax( T ) ) );