参阅《数据结构与算法分析》
二叉查找树性质:对于一个节点,它的左子树的所有节点的值都小于它的值,它的右子树的所有节点的值都大于它的值
1.声明:
#ifdef _Tree_H struct TreeNode; typedef struct TreeNode *Position; typedef struct TreeNode *SearchTree; SearchTree MakeEmpty(SearchTree T); Position Find(int X, SearchTree T); Position FindMin(SearchTree T); Position FindMax(SearchTree T); SearchTree Insert(int X, SearchTree T); SearchTree Delete(int X, SearchTree T); int Retrieve( Position P); #endif
2.结构
struct TreeNode { int value;//为了方便 使其数据域为int SearchTree Left; SearchTree Right; };
3.清空
SearchTree MakeEmpty( SearchTree T) { if(T != NULL) { MakeEmpty(T->Left); MakeEmpty(T->Right); free(T); }//递归清空 return NULL; }
4.查找
Position Find(int X, SearchTree T) { if(T == NULL) { return NULL; } if(X < T->value) return Find(X,T->Left); else if( X > T->value) return Find(X,T->Right); else return T; }
5.查找最小的元素(树的最左边节点)
Position FindMin(SearchTree T) { if(T == NULL) return NULL; if(T->Left != NULL) return FindMin(T->Left); else return T; }
6.查找最大的元素(树的最右边节点)
Position FindMax(SearchTree T) { if(T == NULL) return NULL; if(T->Right != NULL) return FindMax(T->Right); else return T; }
7.插入元素
SearchTree Insert(int X,SearchTree T) { if(T == NULL) { T = malloc(sizeof(struct TreeNode)); if(T == NULL) { printf("out of space"); exit(0); } else { T->value = X; T->Left = NULL; T->Right = NULL; } } else if(X < T->value) T->Left = Insert(X,T->Left); else if(X > T->value) T->Right = Insert(X,T->Right);//一直找到能插入的节点 return T; }
8.删除节点有两种方法
(1) 标记法!!(惰性删除)
(2) 如果一个要删除的这个节点既有左子树,又有右子树,那么这个把右子树的最小值赋给这个节点然后在删除右子树最小值节点(又是一个删除操作) ,如果只有一个子树,父节点接下来即可, 如果为叶子节点,直接删除;
这里贴方法二的代码:
SearchTree Delete(int X,SearchTree T) { Position TmpCell; if(T == NULL) return NULL; if(X < T->value) T->Left = Delete(X,T->Left); else if(X > T->value) T->Right = Delete(X,T->Right); else if(T->Left && T->Right) { TmpCell = FindMin(T->Right); T->value = TmpCell-> value; T->Right = Delete(T->value, T->Right); } else { TmpCell = T; if(T->Left == NULL) { T = T->Right; } else if(T->Right == NULL) { T = T -> Left; } free(TmpCell); } return T; }
原文中的错误处理如下:
#include <stdio.h> #include <stdlib.h> #define Error( Str ) FatalError( Str ) #define FatalError( Str ) fprintf( stderr, "%s ", Str ), exit( 1 )