#include<stdio.h> #include<stdlib.h> typedef struct TreeNode *BinTree; //定义一个对象指针 typedef BinTree Position; //定义一个对象指针名 struct TreeNode{ int Data; BinTree Left; BinTree Right; }; //二叉搜索数的查找Find Position Find(int x,BinTree BST) { if(!BST) //判断BST是否为空 return NULL; if(x > BST->Data) return Find(x,BST->Right); //在右指数继续查找 else if(x < BST->Data) //在左指数继续查找 return Find(x,BST->Left); else return BST; //查找成功 } //二叉搜索数的查找Find 非递归实现 Position IterFind(int x,BinTree BST) { while(BST) { if(x > BST->Data) BST = BST->Right; else if(x < BST->Data) BST = BST->Left; else return BST; } return NULL; } Position FindMin(BinTree BST) { if(!BST) return NULL; else if(!BST->Left) //找到左叶结点并返回 return BST; else return FindMin(BST->Left); } Position FindMax(BinTree BST) { if(BST) while(BST->Right) BST = BST->Right; return BST; } //二叉搜索数的插入算法 适用于带头结点的二叉树 BinTree Insert(int x,BinTree BST) { if(!BST) //判断传入指针是否为空 { BST = new TreeNode; BST->Data = x; BST->Left = BST->Right = NULL; }else if(x < BST->Data) BST->Left = Insert(x,BST->Left); else if(x > BST->Data) BST->Right = Insert(x,BST->Right); return BST; //如果都不执行就返回 } //搜索二叉数的删除 BinTree Delete(int x,BinTree BST) { Position Tmp; if(!BST) printf("删除的元素未找到"); else if(x < BST->Data) BST->Left = Delete(x,BST->Left); else if(x > BST->Data) BST->Right = Delete(x,BST->Right); else { if(BST->Left&&BST->Right) //被删除的结点含有左右两个子结点 { Tmp = FindMin(BST->Right); //在右指数中去找最小值替代被删除元素 BST->Data = Tmp->Data; BST->Right = Delete(BST->Data,BST->Right); //在删除元素的右边去把最小值那个结点删除掉 } else { Tmp = BST; if(!BST->Left) //有右孩纸或无结点 BST = BST->Right; else if(!BST->Right) BST = BST->Left; //有左孩纸或无结点 free(Tmp); } } return BST; } void showBinTree(BinTree BST) { if(BST) //用if判断便于返回 { showBinTree(BST->Left); showBinTree(BST->Right); printf("%d\n",BST->Data); } } int main() { TreeNode *a = new TreeNode; a->Data = 9; a->Left = NULL; a->Right = NULL; a = Insert(5,a); a = Insert(6,a); a = Insert(10,a); a = Insert(13,a); a = Delete(5,a); showBinTree(a); system("pause"); } //测试数据 1 5 2 6 4 //测试数据 9 5 6 10 13
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-26 13:30:47