数据结构与算法分析-二叉查找树
#include <stdio.h> #include <stdlib.h> #define ElementType int //节点数据类型 //typedef struct TreeNode *Position; //typedef struct TreeNode *SearchTree; struct TreeNode { ElementType Element; struct TreeNode *Left; struct TreeNode *Right; }; typedef struct TreeNode *Position; typedef struct TreeNode *SearchTree; SearchTree Insert(ElementType X, SearchTree T); SearchTree Delete(ElementType X, SearchTree T); SearchTree MakeEmpty(SearchTree T); SearchTree PrintTree(SearchTree T); //使用前序遍历打印树 Position Find(ElementType X, SearchTree T); Position FindMax(SearchTree T); Position FindMin(SearchTree T); SearchTree Insert(ElementType X, SearchTree T) { if (NULL == T) { T = (SearchTree)malloc(sizeof(struct TreeNode)); if (NULL == T) { printf("Malloc Error!\n"); return NULL; } else { printf("Insert %d!\n", X); T->Element = X; T->Left = T->Right = NULL; } } else if (X > T->Element) { T->Right = Insert(X, T->Right); } else { T->Left = Insert(X, T->Left); } return T; }
//删除的效率并不高,因为它沿该树进行了两趟搜索以查找和删除右子树中最小的节点.
//经过大量删除操作后,将会导致左子树比右子树深,原因是我们总是用右子树的一个节点来代替删除节点 SearchTree Delete(ElementType X, SearchTree T) { Position Temp = NULL; if (NULL == T) { printf("Delete Element Not Found!\n"); return NULL; } else if (X > T->Element) { T->Right = Delete(X, T->Right); } else if (X < T->Element) { T->Left = Delete(X, T->Left); } else if (T->Right && T->Left) { Temp = FindMin(T->Right); T->Element = Temp->Element; T->Right = Delete(T->Element, T->Right); } else { Temp = T; if (NULL == T->Right) { T = T->Left; } else if (NULL == T->Left) { T = T->Right; } else {} free(Temp); Temp = NULL; } return T; } SearchTree MakeEmpty(SearchTree T) { if (NULL != T) { MakeEmpty(T->Right); MakeEmpty(T->Left); free(T); } return NULL; } SearchTree PrintTree(SearchTree T) { if (NULL != T) { printf("%d ", T->Element); if (NULL != T->Left) { PrintTree(T->Left); } if (NULL != T->Right) { PrintTree(T->Right); } } return NULL; } Position Find(ElementType X, SearchTree T) { if (NULL == T) { printf("Find Element Not Found!\n"); return NULL; } else if (X < T->Element) { return Find(X, T->Left); } else if (X > T->Element) { return Find(X, T->Right); } else { return T; } } Position FindMax(SearchTree T) { if (NULL != T) { while (NULL != T->Right) { T = T->Right; } } return T; } Position FindMin(SearchTree T) { if (NULL == T) { return NULL; } else if (NULL == T->Left) { return T; } else { return FindMin(T->Left); } } int main() { SearchTree T = NULL; SearchTree ptmp = NULL; T = Insert(6, T); T = Insert(2, T); T = Insert(8, T); T = Insert(4, T); T = Insert(3, T); T = Insert(1, T); ptmp = FindMin(T); if (NULL != ptmp) { printf("min:%d\n", ptmp->Element); } ptmp = FindMax(T); if (NULL != ptmp) { printf("max:%d\n", ptmp->Element); } ptmp = Find(3, T); if (NULL != ptmp) { printf("find:%d\n", ptmp->Element); } PrintTree(T); printf("\n"); T = Delete(3, T); PrintTree(T); printf("\n"); ptmp = Find(3, T); if (NULL != ptmp) { printf("find:%d\n", ptmp->Element); } T = MakeEmpty(T); return 0; }