二叉树的基本操作

来源:互联网 发布:非常完美知乎 编辑:程序博客网 时间:2024/05/21 21:48
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<queue>using namespace std;struct node{int data;struct node* left;struct node* right;};typedef struct node* Tree;Tree Insert(Tree Bt,int data){if(!Bt){Bt=(Tree)malloc(sizeof(struct node));Bt->data=data;Bt->left=Bt->right=NULL;}else if(data<Bt->data) Bt->left=Insert(Bt->left,data);else  Bt->right=Insert(Bt->right,data);return Bt;}bool Find(Tree Bt,int x){if(!Bt) return false;else{if(x<Bt->data) Find(Bt->left,x);else if(x>Bt->data) Find(Bt->right,x);else return true;}}Tree FindMin(Tree Bt){if(!Bt) return NULL;else if(Bt->left==NULL) return Bt;else return FindMin(Bt->left);}/*Tree FindMin(Tree Bt){  //µü´úÕÒ×îСֵ if(!Bt) return NULL;while(!Bt->left)    Bt=Bt->left;return Bt;}*/Tree FindMax(Tree Bt){if(!Bt) return NULL;else if(Bt->right==NULL) return Bt;else return FindMax(Bt->right);}/*Tree FindMax(Tree Bt){   //µü´úÕÒ×î´óÖµif(!Bt) return NULL;while(!Bt->right)Bt=Bt->right;return Bt;}*/Tree Delete(Tree Bt,int x){Tree temp;if(!Bt) return NULL;if(x<Bt->data) Bt->left=Delete(Bt->left,x);else if(x>Bt->data) Bt->right=Delete(Bt->right,x);else{if(Bt->left&&Bt->right){temp=FindMin(Bt->right);Bt->data=temp->data;Bt->right=Delete(Bt->right,Bt->data);}else{temp=Bt;if(!Bt->left) Bt=Bt->right;else Bt=Bt->left;free(temp);}      }return Bt;}Tree MakeEmpty(Tree Bt){if(Bt){MakeEmpty(Bt->left);MakeEmpty(Bt->right);free(Bt);}return NULL;}void PreOrderSearch(Tree Bt){if(Bt){printf("%d ",Bt->data);PreOrderSearch(Bt->left);PreOrderSearch(Bt->right);}}void InOrderSearch(Tree Bt){if(Bt){InOrderSearch(Bt->left);printf("%d ",Bt->data);InOrderSearch(Bt->right);}}void PostOrderSearch(Tree Bt){if(Bt){PostOrderSearch(Bt->left);PostOrderSearch(Bt->right);printf("%d ",Bt->data);}}void LevelOrderSearch(Tree Bt){queue<Tree>p;if(Bt) p.push(Bt);while(!p.empty()){Tree temp=p.front();p.pop();printf("%d ",temp->data);if(temp->left) p.push(temp->left);if(temp->right) p.push(temp->right);}}int main(){int n;scanf("%d",&n);Tree Bt=NULL;for(int i=0;i<n;i++){int data;scanf("%d",&data);Bt=Insert(Bt,data);}PreOrderSearch(Bt);printf("\n");LevelOrderSearch(Bt);Tree Maxpos = FindMax(Bt);if(Maxpos) printf("%d\n",Maxpos->data);Bt=Delete(Bt,7);InOrderSearch(Bt);printf("%\n");return 0;}