二叉查找树实现
二叉查找樹聲明
#ifndef _Tree_Hstruct TreeNode; typedef struct TreeNode *Position; typedef struct TreeNode *SearchTree;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);#endifsrtuct TreeNode {ElementType Element;SearchTree Left;SearchTree Right; };建立一顆空樹
SearchTree MakeEmpty(SearchTree T) {if(T != NULL){MakeEmpty(T->Left);MakeEmpty(T->Right);Free(T);}return NULL; }二叉查找樹的Find操作
Position Find(ElementType X,SearchTree T) {if(T == NULL)return NULL;if( X < T->Element)return Find(X,T->Left)else if( X > T->Element)return Find(X,T->Right)else return T; }二叉查找樹的FindMin遞歸實現
Position FindMin(SearchTree T) {if(T == NULL)return NULL;else if( T->Left == NULL)return T;elsereturn FindMin(T->Left); }二叉查找樹的FindMin非遞歸實現
Position FindMin(SearchTree T) {if(T != NULL)while(T->Left != NULL)T = T->Left;return T; }二叉查找樹的FindMax遞歸實現
Position FindMax(SearchTree T) {if(T == NULL)return NULL;else if( T->Right == NULL)return T;elsereturn FindMax(T->Right); }二叉查找樹的FindMax非遞歸實現
Position FindMax(SearchTree T) {if(T != NULL)while(T->Right != NULL)T = T->Right;return T; }二叉查找樹的插入操作
SearchTree Insert(ElementType X,SearchTree T) {if(T == NULL){T = malloc(sizeof(struct TreeNode));if(T == NULL)FatalError("Out of space!!!");else{T->Element = X;T->Left = T->Right = NULL;}}else if(X < T->Element)T->Left = Insert(X,T->Left);else if( X > T->Element)T->Right = Insert(X,T->Right);return T; }二叉查找樹的刪除操作
SearchType Delete(ElementType X,SearchTree T) {Position TmpCell;if(T == NULL)Error("Element not found");else if(X < T->Element)T->Left = Delete(X,T->Left);else if(X > T->Element)T->Right = Delete(X,T->Right);else if(T->Left && T->Right){TmpCell = FindMin(T->Right);T->Element = TmpCell->Element;T->Right = Delete(T->Element,T->Right);}else{TmpCell = T;if(T->Left == NULL)T = T->Right;else if(T->Right == NULL)T = T->Left;free(TmpCell);}return T; }轉載于:https://www.cnblogs.com/y3w3l/p/6363506.html
總結
- 上一篇: 洛谷 P 1387 最大正方形
- 下一篇: Longest Substring Wi