BST的插入,中序遍历,删除,求前驱,求后继,求最大,最小值的操作。 参考算导~ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> using namespace std; typedef struct BST{ int key; BST *lchild,*rchild,*parent; // 存左右孩子以及父节点 }BST; BST *head,*p,node[100]; int cou; void init() { head = p = NULL; cou = 0 ; memset(node,'/0',sizeof(node)); } void BuildBST(BST *&head,int x) // 创建BST,即BST的插入~ { if( head == NULL ) { node[cou].key = x; node[cou].parent = p; head = &node[cou++]; return ; } p = head; if( head->key > x ) BuildBST(head->lchild,x); else BuildBST(head->rchild,x); } void InorderTraver(BST *head) // 中序遍历 { if( head == NULL ) return ; InorderTraver( head->lchild ); cout << head->key << ' ' ; InorderTraver( head->rchild ); } BST* Search( BST *&head,int x )//在BST中查找key为x的值 { if( head->key == x ) { p = head; return head; } if( head->key > x ) Search(head->lchild,x); else Search(head->rchild,x); } BST* Minmum(BST* head) // 返回BST中最小值 { while( head->lchild != NULL ) head = head->lchild; return head; } BST *Maxmum( BST* head ) // 返回BST中最大值 { while( head->rchild != NULL ) head = head->rchild; return head; } BST* Successor(BST *head) // 返回节点head的后继节点 { if( head->rchild != NULL ) return Minmum(head->rchild); BST* y = head->parent; while( y != NULL && head == y->rchild ) { head = y; y = y->parent; } return y; } BST* Predecessor(BST *head) // 返回节点head的前驱节点 { if( head->lchild != NULL ) return Maxmum(head->lchild); BST* y = head->parent; while( y != NULL && head == y->lchild ) { head = y; y = y->parent; } return y; } void Delet(BST *z) //删除节点z { BST *x,*y; if( z->lchild == NULL || z->rchild == NULL ) y = z; else y = Successor(z); if( y->lchild != NULL ) x = y->lchild; else x = y->rchild; if( x != NULL ) x->parent = y->parent; if( y->parent == NULL ) head = x; else if( y == y->parent->lchild ) y->parent->lchild = x; else y->parent->rchild = x; if( y != z ) z->key = y->key; } int main() { int x; while( cin >> x && x) BuildBST(head,x); InorderTraver(head); //中序遍历输出 cout << endl; while( cin >> x ) { BST *z; Search(head,x); z = p; Delet(z); if( head == NULL ) break; InorderTraver(head); //删除一个 中序遍历一次 } system("pause"); return 0; }