二叉树查找
1.对象:无重复数字
2.查找代码
Bts_node* search_Bts(Bts_node *bt,int k) { if(bt==NULL||bt->data==k) return bt; if(k<bt->data) return search_Bts(bt->lchild,k); else return search_Bts(bt->rchild,k); }
3.删除代码
void delete2(Bts_node *p,Bts_node *&r) { Bts_node *q; if(r->rchild!=NULL)//找到最大的节点(右边大),用while也许也行 delete2(p,r->rchild); else { p->data=r->data; q=r; r=r->lchild; delete(q); } } void delete1(Bts_node *&p) { Bts_node *q; if(p->rchild==NULL)//只有左子树 { q=p; p=p->lchild; delete(q); } else if(p->lchild==NULL)//只有右子树 { q=p; p=p->rchild; delete(q); } else delete2(p,p->lchild); } bool delete_Bts(Bts_node *&bt,int k) { if(bt==NULL) return false; else { if(k<bt->data) return delete_Bts(bt->lchild,k); else if(k>bt->data) return delete_Bts(bt->rchild,k); else { delete1(bt); return true; } } }
4.实例:
#include<iostream> using namespace std; struct Bts_node { int data; Bts_node *lchild,*rchild; }; bool insert_Bts(Bts_node *&bt,int k) { if(bt==NULL) { bt=new Bts_node; bt->data=k; bt->lchild=bt->rchild=NULL; } if(k==bt->data) return false; else { if(k>bt->data) insert_Bts(bt->rchild,k); else insert_Bts(bt->lchild,k); } } Bts_node *create_Bts(int n) { Bts_node *bt=NULL; for(int i=0;i<n;i++) { int temp; cin>>temp; insert_Bts(bt,temp); } return bt; } Bts_node* search_Bts(Bts_node *bt,int k,Bts_node *f,Bts_node *&f1) { if(bt==NULL) { f1=NULL; return NULL; } else if(bt->data==k) { f1=f; return bt; } else if(k<bt->data) return search_Bts(bt->lchild,k,bt,f1); else return search_Bts(bt->rchild,k,bt,f1); } void print(Bts_node *b1) { if(b1!=NULL) { cout<<b1->data; if(b1->lchild!=NULL||b1->rchild!=NULL) { cout<<"("; print(b1->lchild); if(b1->rchild!=NULL) { cout<<","; print(b1->rchild); } cout<<")"; } } } Bts_node* search_Bts(Bts_node *bt,int k) { if(bt==NULL||bt->data==k) return bt; if(k<bt->data) return search_Bts(bt->lchild,k); else return search_Bts(bt->rchild,k); } int main() { Bts_node *bt,*f1; int n; cout<<"n="; cin>>n; bt=create_Bts(n); int k; cout<<"k="; cin>>k; cout<<search_Bts(bt,k,NULL,f1)->data<<endl;//找双亲 +k cout<<search_Bts(bt,k)->data<<endl;//只 找 K print(bt); delete_Bts(bt,k); print(bt); return 0; }