#include<iostream.h>
#include<stdio.h>
#include<conio.h>
struct node
{
node *left;
node *right;
node *parent;
char ch;
int wt;
int val;
};
int m,n;
node *a[30],*b[30];
void sort()
{
node *temp;
for(int i=0;i<m-1;i++)
{
for(int j=i+1;j<m;j++)
{
if(a[i]->wt>a[j]->wt)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void maketree()
{
node *ptr;
ptr=new node;
ptr->wt=a[0]->wt+a[1]->wt;
ptr->left=a[0];
ptr->right=a[1];
a[0]->parent=ptr;
a[1]->parent=ptr;
a[0]->val=0;
a[1]->val=1;
a[0]=ptr;
for(int i=1;i<m;i++)
{
a[i]=a[i+1];
}
n–;
}
/*void display(int m)
{
for(int i=0;i<m;i++)
{
cout<<“\nname”<<n[i].ch;
cout<<“\t wt”<<n[i].wt;
}
} */
int p[10],j;
void print2(int i)
{
cout<<b[i]->ch;
for(int k=j-1;k>=0;k–)
{
cout<<p[k];
}
cout<<“\n”;
}
void bincode()
{ node *ptr,*ptr2;
ptr=a[0];
for(int i=0;i<m;i++)
{
ptr2=b[i];
j=0;
while(ptr2!=ptr)
{
p[j]=ptr2->val;
j++;
ptr2=ptr2->parent;
}
print2(i);
}
}
void main()
{
clrscr();
cout<<“\nEnter size”;
cin>>m;
n=m;
cout<<“\nEnter tree”;
for(int i=0;i<m;i++)
{
a[i]=new node;
cout<<“Enter Name\n”;
cin>>a[i]->ch;
cout<<“Enter weight”;
cin>>a[i]->wt;
a[i]->right=NULL;
a[i]->left=NULL;
a[i]->parent=NULL;
b[i]=a[i];
}
n–;
while(n!=0)
{
sort();
maketree();
}
bincode();
//display(m);
getch();
}
Theory: