struct TreeNode{ SearchTree Left; SearchTree Right; ElementType Ele; }; /*递归一定有出口*/ /*递归代码就是要重复使用*/ SearchTree Insert( SearchTree T, X ) { /*这个是对树中没有该参数,增加节点*/ if( T == NULL ) { T = malloc( sizeof( struct TreeNode ) ); if( T == NULL ) fatalError(); T->Ele = X; T->Left = NULL; T->Right = NULL: } /*继续比较*/ else if(T->Ele > X ) T->Left = Insert( T->Left, X );//对于没有左子节点,返回新建节点指针,若有,在递归返回时,则相当于什么都没做 else if( T->Ele < X ) T->Right = Insert( T->Right, X ); return T; } SearchTree FindMin(SearchTree T ) { if(T == NULL) return NULL;//只针对第一次 if( T->Left != NULL ) return FindMin( T->Left ); return T; } //二叉查找树的删除例程 SearchTree Delete( SearchTree T, ElementType X ) { S earchTree TmpCell; if( T == NULL ) Error("no Element found"); if( T->Ele > X ) T->Left = Delete( T->Left, X ); else if( T->Ele < X ) Delete( T->Right, X ); else if( T->Right && T->Left ) { TmpCell = FindMin(T->Right); T->Ele = TmpCell->Ele; Delete( TmpCell, T->Ele ); } else//供给1.删除只有一个或没有儿子的父节点2.删除右子树最小节点 { if( T->Left == NULL ) T = T->Right; else if(T->Right == NULL ) T = T->Left; } return T; }
时间: 2024-10-06 00:22:30