Escolar Documentos
Profissional Documentos
Cultura Documentos
# include<conio.h>
#include<math.h>
using namespace std;
class binarytree{
binarytree *leftchild,*rightchild,*parent;
int value;
public:
binarytree* add(binarytree *root){
binarytree *temp,*p; int element;
int i=0,j=0;
temp=root;
binarytree *newone= new binarytree;
cout<<"\nenter the element to be added: "; cin>>element;
newone->value=element; newone->leftchild=NULL; newone->rightchil
d=NULL; newone->parent=NULL;
if(root==NULL){
root=newone;
y[j]=root;
y[2*j+1]=NULL;
y[2*j+2]=NULL;
}else{
while(1){
if(element<=temp->value)
{
j=2*j+1;
if(temp->leftchild==NULL){
temp->leftchild=newone;
y[j]=newone;
if(j%2==0)
y[(j-2)/2]->rightchild=y
[j];
else
y[j/2]->leftchild=y[j];
y[2*j+1]=NULL;
y[2*j+2]=NULL;
break;
}
else{
p=temp;
temp=temp->leftchild;
}
}
else{
j=2*j+2;
if(temp->rightchild==NULL){
temp->rightchild=newone;
y[j]=newone;
if(j%2==0)
y[(j-2)/2]->rightchild=y
[j];
else
y[j/2]->leftchild=y[j];
y[2*j+1]=NULL;
y[2*j+2]=NULL;
break;
}
else{
p=temp;
temp=temp->rightchild;
}
}
}
}
return root;
}
j=0;
while(1){
if(temp->value==element){
flag=1;
break;
}
if(element<temp->value){
p=temp;
temp=temp->leftchild;
j=2*j+1;
}
if(element>temp->value){
p=temp;
temp=temp->rightchild;
j=2*j+2;
}
if(temp==NULL){
break;
}
if(flag==1){
cout<<"\nj value is "<<j;
if(y[2*j+1]==NULL && y[2*j+2]==NULL){
cout<<"\nyou are deleting a leaf node ";
y[j]=NULL;
if(rootalert==0){
if(j%2==0){
y[(j-2)/2]->rightchild=N
ULL;
}
else{
y[j/2]->leftchild=NULL;
}
}
else if(y[2*j+2]==NULL) {
x=0;
if(rootalert==0){
if(j%2==0)
y[(j-2)/2]->rightchild=y
[2*j+1];
else
y[j/2]->leftchild=y[2*j+
1];
}
j=2*j+1;
while(1){
k=0;
l=-1;
for(int i=j;i<(j+pow(2,x));i++){
y[(i+l)/2]=y[i] ;
l++;
if((i/2)==0){
root=y[i];
y[i/2]->leftchil
d=y[2*i+1];
}
if(y[i]==NULL)
k++;
y[i]=NULL;
}
if(k==pow(2,x))
break;
x++;
j=2*j+1;
}
}
else{
j=2*j+2;
k=j;
while(1){
if(y[2*k+1]==NULL)
break;
else
k=2*k+1;
}
j=(j-2)/2;
if(rootalert==0){
if(j%2==0)
y[(j-2)/2]->rightchild=y
[k];
else
y[j/2]->leftchild=y[k];
}
y[j]=y[k];
y[k]=NULL;
y[j]->leftchild=y[2*j+1];
y[j]->rightchild=y[2*j+2];
if(k==(2*j+2))
y[(k-2)/2]->rightchild=y[2*k+2];
else
y[k/2]->leftchild=y[2*k+2];
if(j==0)
root=y[j];
k=2*k+2; x=0;
l=-2; s=-2;
while(1){
j=0;
for(int i=k;i<(k+pow(2,x));i++){
y[(i+s)/2]=y[i];
s++;
if(y[i]==NULL)
j++;
y[i]=NULL;
}
if(j==pow(2,x))break;
l=l-pow(2,x);
s=l;
x++; k=2*k+1;
}
return root;
}
}
}
if(x==pow(2,j+1))
break;
j++;
}
cout<<"\n the j value is:"<<j;
x=0; int row=0;
for(i=0;i<(pow(2,j+1)-1);i++){
if(i==x){
cout<<"\n\nelements in row "<<row<<": ";
row++;
x=pow(2,row)-1;
}
if(y[i]==NULL)
cout<<"NULL\t" ;
else
cout<<y[i]->value<<"\t";
}
}
}*y[100];
void main(){
char c; int t=0;
binarytree *root; root=NULL;