首页 > 代码库 > 二叉查找树(二叉排序树)(C语言)
二叉查找树(二叉排序树)(C语言)
#include<stdio.h>#include "fatal.h"struct TreeNode;typedef struct TreeNode *Position;typedef struct TreeNode *SearchTree;typedef int ElementType;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);struct TreeNode { ElementType Element; SearchTree left; SearchTree right;};SearchTree MakeEmpty(SearchTree T){ if(T!=NULL) { MakeEmpty(T->left); MakeEmpty(T->right); free(T); } return NULL;}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;}Position FindMin(SearchTree T){ if(T==NULL) return NULL; if(T->left==NULL) return T; else return FindMin(T->left);}Position FindMax(SearchTree T){ if(T==NULL) return NULL; else if(T->right==NULL) return T; else return FindMax(T->right);}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;}SearchTree Delete(ElementType X,SearchTree T){ Position TmpCell; if(T==NULL) Error("Error 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(X,T->right); } else { TmpCell=T; if(T->left==NULL) T=T->right; else if(T->right=NULL) T=T->left; free(TmpCell); } return T;}ElementType Retrieve(Position P){ if(P==NULL) return -1; else return P->Element;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。