注册 登录
编程论坛 C++教室

平衡二叉树[原创]

kings169524 发布于 2005-05-06 15:09, 2121 次点击

这个东东就是要花一点时间画图研究。 以下是我的代码。 写得差请见谅 #include <status.h>

typedef struct BT{ int data; struct BT* l; struct BT* r; int bl; BT(int d); }BT;

BT::BT(int d){ l=r=NULL; data=d; bl=0; }

void clear(BT* p){ if(p){ clear(p->l); clear(p->r); delete(p); } }

void print(BT* p){ cout<<"data="<<p->data<<'\t'<<"bl="<<p->bl<<endl; }

void f_p(BT* T){ if(T!=NULL){ print(T); f_p(T->l); f_p(T->r); } }

void m_p(BT* T){ if(T!=NULL){ m_p(T->l); print(T); m_p(T->r); } }

void Trans(BT* T){ cout<<"\nfront trans:\n"; f_p(T); cout<<endl; cout<<"\nmid trans:\n"; m_p(T); cout<<endl; }

void Rotate_1(BT* &p){ BT* T=p->l; p->bl=0; T->bl=0; p->l=T->r; T->r=p; p=T; }

void Rotate_2(BT* &p){ BT* T=p->l->r; if(T->bl==0){ p->l->bl=p->bl=0; } else{ if(T->bl==1){ p->bl=-1; } else{ p->l->bl=1; } } p->l->r=T->l; T->l=p->l; p->l=T->r; T->r=p; p=T; }

void Rotate_3(BT* &p){ BT* T=p->r; p->bl=T->bl=0; p->r=T->l; T->l=p; p=T; }

void Rotate_4(BT* &p){ BT* T=p->r->l; if(T->bl==0){ p->r->bl=p->bl=0; } else{ if(T->bl==1){ p->r->bl=-1; } else{ p->bl=1; } } p->r->l=T->r; T->r=p->r; p->r=T->l; T->l=p; p=T; }

void Avl_Tree(BT* &p){ if(p->bl==2){ if(p->l->bl==1) Rotate_1(p); else Rotate_2(p); } else{ //p->bl==-2 if(p->r->bl==-1) Rotate_3(p); else Rotate_4(p); } }

status _Insert(int d,BT* &p,short int &f,short int &af){ if(!p){ p=new BT(d); f=SUCCESS; return TRUE; } else{ if(d>p->data){ if(_Insert(d,p->l,f,af)){ if(!p->r) af=TRUE; else{ af=FALSE; p->bl++; } } if(af==TRUE){ p->bl++; if(p->bl==2){ Avl_Tree(p); af=FALSE; } } } else if(d<p->data){ if(_Insert(d,p->r,f,af)){ if(!p->l) af=TRUE; else{ af=FALSE; p->bl--; } } if(af==TRUE){ p->bl--; if(p->bl==-2){ Avl_Tree(p); af=FALSE; } } } else{ f=FAILE; } return FALSE; } }

status Insert(int d,BT* &p){ short int f=SUCCESS; short int af=FALSE; _Insert(d,p,f,af); return f; }

void t1(){ BT* p=NULL; int d=1; cout<<"insert data="; cin>>d; while(d!=0){ if(Insert(d,p)) cout<<"\tInsert success"<<endl; else cout<<"\tInsert failed"<<endl; cout<<"insert data="; cin>>d; } Trans(p); getch(); clear(p); }

void main(){ t1(); }

9 回复
#2
玩偶2005-09-15 11:30
楼主的头文件是自己写的吧??
#3
witchery2005-09-16 20:18
什么是"二叉树" , 讲解一下吧. 初学者 不太了解
#4
slp0010022005-12-08 12:26
&lt;status.h&gt;
#5
slp0010022005-12-08 12:28
&lt;status.h&gt;是个头文件吧,在Visual C++执行中应该写清楚&lt;status.h&gt;原代码吧
#6
ElfDN2005-12-09 14:32

晕,怎么不用递归?
斑竹,一起来帮忙优化

#7
benter2005-12-11 18:10
楼主上传一下头文件塞
#8
nqq6222006-05-17 10:58
#9
ltxbs812010-05-06 00:38
诸位好,小弟遇到了一道难题:
已知某排序平衡二叉树T具有下列特点:
(1)结点的关键字均在1到9范围为内;
(2)在T中存在一个关键字为n1的叶结点,若删去该结点,立即插入一个关键字为n1的结点,得到的平衡树与原T不同;
(3)在T中存在一个关键字为n2的非叶结点,若删去该结点,立即插入n2结点,得到与原T相同的平衡树;
(4)在T中插入某n3结点并立即删去它,得到的平衡树与原T不同。
试通过程序输出具有上述特点的最简单(结点个数最少)的平衡二叉树T,并写明n1,n2,n3分别等于几?
恳请大家帮忙解决,谢谢!
#10
菜鸟,求帮忙2015-07-15 15:49
二叉树哪位讲解一下
1