struct node{ int data; node* lch,*rch; }; node* insert(node* p,int x){ if(p==NULL){ node* q = new node; q->data = x; q->lch = q->rch = NULL; return q; }else{ if(x<p-data) p->lch = (p->lch,x); else p->rch = insert(p->rch,x); return p; } } bool find(node* p,int x){ if(p==NULL) return false; if(x<p->data) return find(p->lch,x); else if(x==p->data) return true; else return find(p->rch,x); } node* remove(node* p,int x){ //分三种情况考虑 if(p==NULL) return NULL; else if(x<p->data) p->lch = remove(p->lch,x); else if(x>p->data) p->rch = remove(p->rch,x); else if(p->lch == NULL){ node* q = p->rch; delete p; return q; }else if(p->lch->rch == NULL){ node * q = p->lch;//直接将左孩子提上去,将新节点的右孩子就是原来删除节点的右孩子。 q->rch = p->rch; delete p; return q; }else{ node* q; for(q=p->lch;q->rch->rch!=NULL;q=q->rch); node* r = q->rch; q->rch =r->lch; r->lch = p->lch; r->rch = p->rch; delete p; return r; } }
#include <iostream> using namespace std; const int MAX = 100; int par[MAX],rank[MAX]; void init(int n){ for(int i=0;i<n;i++){ par[i] = i;//没有边 rank[i] = 0; } } int find(int x){ if(par[x]==x) return x; else return par[x] = find(par[x]); } void unite(int x,int y){ x = find(x); y = find(y); if(x==y) return; if(rank[x]<rank[y]){ par[x] = y; }else{ par[y] = x; if(rank[x]==rank[y]){ rank[x]++; } } } bool same(int x,int y){ return find(x) == find(y); }
原文地址:http://blog.csdn.net/xd_122/article/details/40659179