(+84) 236.3827111 ex. 402

BST_CanBang


#include
using namespace std;
struct Cay{
int dulieu;
Cay *trai, *phai;
};
void LNR(Cay *&t){
if(t!=NULL){
LNR(t->trai);
cout<dulieu<<" ";
LNR(t->phai);
}
}
void sapXep(int a[], int n){
for(int i=1;i<>
for(int j=i+1;j<=n;j++){
if(a[i]>a[j]){
int tg=a[i];
a[i]=a[j];
a[j]=tg;
}
}
}
}
int demNode(Cay *&t){
if(t==NULL) return 0;
else return 1+demNode(t->trai)+demNode(t->phai);
}
void chenCB(int x, Cay *&t){
if(t==NULL){
t= new Cay;
t->dulieu=x;
t->trai=t->phai=NULL;
}
else if(demNode(t->trai)<=demNode(t->phai)) chenCB(x,t->trai);
else chenCB(x,t->phai);
}
int x=1;
void taoBST(Cay *&t, int a[]){
if(t!=NULL){
taoBST(t->trai,a);
t->dulieu=a[x];x++;
taoBST(t->phai,a);
}
}
int main(){
Cay *t=NULL;
int n,a[100];
do{
cout<<"Nhap so luong node: ";cin>>n;
}while(n<=0);
cout<<"Nhap danh sach "<
for(int i=1;i<=n;i++){
cin>>a[i];
chenCB(a[i],t);
}
sapXep(a,n);
taoBST(t,a);
cout<<"\n\nDuyet LNR cay CB&BST: ";LNR(t);
}