数据结构与算法分析-二叉查找树的实现

 

 

 #ifndef _BINARY_SEARCH_TREE_H #define _BINARY_SEARCH_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 ); void PrintTree( SearchTree T ); #endif

 

#include <stdio.h> #include <assert.h> #include <malloc.h> #include “binarysearchtree.h” struct TreeNode { int Element; SearchTree Left; SearchTree Right; }; SearchTree MakeEmpty( SearchTree T ) { if ( T != NULL ) { MakeEmpty( T->Left ); MakeEmpty( T->Right); free( T ); } return NULL; } Position Find( int 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; else if( T->Left == NULL ) return T; else return FindMin( T->Left ); } Position FindMax( SearchTree T ) { if( T != NULL ) while( T->Right != NULL ) T = T->Right; return T; } SearchTree Insert( int X, SearchTree T ) { if ( T == NULL ) { T = malloc( sizeof(struct TreeNode)); assert( T!= NULL); 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( int X, SearchTree T ) { Position TmpCell; if ( T == NULL ) { printf(“Element not found/n”); } 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; } void PrintTree( SearchTree T ) { if ( T != NULL ) { printf(“–%d–/n–|–/n”, T->Element ); if ( T->Left != NULL ) { printf(“–LEFT–/n”); PrintTree( T->Left ); } if ( T->Right != NULL ) { printf(“–RIGHT–/n”); PrintTree( T->Right ); } } } int main(int argc, char **argv) { SearchTree prtTree = NULL; SearchTree tmp; prtTree = Insert(7, prtTree ); prtTree = Insert( 4, prtTree ); prtTree = Insert( 3, prtTree ); prtTree = Insert( 11, prtTree ); prtTree = Insert( 8, prtTree ); prtTree = Insert( 14, prtTree ); prtTree = Insert( 12, prtTree ); prtTree = Insert( 13, prtTree ); PrintTree( prtTree); prtTree = Delete( 11, prtTree ); PrintTree( prtTree); tmp = Find( 4, prtTree ); printf(“########%d/n”, tmp->Left->Element); tmp = FindMax( prtTree ); printf(“#####Max###%d/n”, tmp->Element); tmp = FindMin( prtTree ); printf(“#####Min###%d/n”, tmp->Element); return 0; }

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/su_yong/article/details/4750411
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞