二叉数组的创建删除插入查找

来源:互联网 发布:国际长途网络电话软件 编辑:程序博客网 时间:2024/06/04 20:04
#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);elsereturn 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;elsereturn BST;}return NULL;}Position FindMin(BinTree BST){if(!BST)return NULL;else if(!BST->Left)     //找到左叶结点并返回return BST;elsereturn 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

1 0