二叉排序树

发布时间 2023-12-30 13:26:45作者: 小菜碟子
  1 #include <iostream>
  2 #include <fstream>
  3 using namespace std;
  4 
  5 struct Tnode
  6 {
  7     int data;
  8     Tnode *lchil,*rchil;
  9 };
 10 
 11 // 向二叉排序树种插入固定值的节点
 12 void insert(Tnode**t,int a)
 13 {
 14     // 如果*t所指为空则进行插入
 15     if(*t == NULL)
 16     {
 17         *t = (Tnode *)malloc(sizeof(Tnode));
 18         (*t)->data = a;
 19         (*t)->lchil = NULL;
 20         (*t)->rchil = NULL;
 21     }
 22     // 进行判断,是否到达要插入的地方
 23     else if((*t)->data > a)
 24     {
 25         // 插入数小于节点数
 26         insert(&(*t)->lchil,a);
 27     }
 28     else if((*t)->data < a)
 29     {
 30         // 插入数大于节点数
 31         insert(&(*t)->rchil,a);
 32     }else 
 33     {
 34         // 插入数等于节点数
 35         printf("该节点已存在,请重新选择其他数插入\n");
 36         return;
 37     }
 38 }
 39 
 40 void deletenode(Tnode**t,int key)
 41 {
 42     if((*t)->data>key)
 43     {
 44         deletenode(&(*t)->lchil,key);
 45     }
 46     else if((*t)->data<key)
 47     {
 48         deletenode(&(*t)->rchil,key);
 49     }
 50     else if((*t)->data==key)
 51     {
 52          (*t)=NULL;
 53     }
 54 }
 55 
 56 int enquiry(Tnode*t,int key)
 57 {
 58     if(t==NULL)
 59     {
 60         return 0;
 61     }
 62     else if(t->data>key)
 63     {
 64         enquiry(t->lchil,key);
 65     }
 66     else if(t->data<key)
 67     {
 68         enquiry(t->rchil,key);
 69     }
 70     else if(t->data==key)
 71     {
 72         return 1;
 73     }
 74 }
 75 
 76 void createBTree(Tnode**t,int nums[],int len)
 77 {
 78   *t = NULL;
 79   for(int i = 0;i < len;i++)
 80   {
 81     insert(t,nums[i]);
 82   } 
 83 }
 84 
 85 void preorder(Tnode*t)
 86 {
 87     if(t==NULL)
 88     {
 89         return;
 90     }
 91     else
 92     {
 93         cout<<t->data<<" ";
 94         preorder(t->lchil);
 95         preorder(t->rchil);
 96     }
 97 }
 98 
 99 int main()
100 {
101     Tnode* t = NULL;
102     int nums[] = {68 ,50 ,60 ,18 ,88 ,12 ,30 ,70 ,48 ,98 ,76 ,58 ,65};
103     int len = 13;
104     createBTree(&t,nums,len);
105     preorder(t);
106     cout<<endl;
107     int i;
108     cin>>i;
109     int result=enquiry(t,i);
110     if(result==0)
111     {
112         cout<<i<<"不存在";
113     }
114     else
115     {
116         deletenode(&t,i);
117         preorder(t);
118     }
119 }