Hello there!
Im making a huffman tree and im having troubles with the pointers. For somereason its not giving the correct output. The problem is where the l2 nodes are pointing.
#include <iostream>
/*
A=7 B=2 C=2 D=3 E=11 F=2 G=2
H=6 I=6 J=1 K=1 L=4 M=3 N=7
O=9 P=2 Q=1 R=6 S=6 T=8 U=4
V=1 W=2 X=1 Y=2 Z=1
*/
using namespace std;
typedef struct Node *BST;
struct Node{
int freq;
char letter;
Node *right;
Node *left;
};
Node * createNode(){
struct Node *new1;
new1 = (struct Node*) malloc(sizeof(struct Node));
return new1;
}
Node fillLeaf(char letter, int freq){
Node new1;
new1.letter = letter;
new1.freq = freq;
new1.left = NULL;
new1.right = NULL;
return new1;
}
Node fillParent(Node l1, Node l2){
Node new1;
new1.freq = l1.freq + l2.freq;
new1.right = &l1;
new1.left = &l2;
return new1;
}
void main(){
int x = 25;
Node leaf[26];
leaf[0] = fillLeaf('e',11);
leaf[1] = fillLeaf('o',9);
leaf[2] = fillLeaf('t',8);
leaf[3] = fillLeaf('a',7);
leaf[4] = fillLeaf('n',7);
leaf[5] = fillLeaf('i',6);
leaf[6] = fillLeaf('s',6);
leaf[7] = fillLeaf('r',6);
leaf[8] = fillLeaf('h',6);
leaf[9] = fillLeaf('l',4);
leaf[10] = fillLeaf('u',4);
leaf[11] = fillLeaf('d',3);
leaf[12] = fillLeaf('m',3);
leaf[13] = fillLeaf('c',2);
leaf[14] = fillLeaf('f',2);
leaf[15] = fillLeaf('p',2);
leaf[16] = fillLeaf('y',2);
leaf[17] = fillLeaf('g',2);
leaf[18] = fillLeaf('w',2);
leaf[19] = fillLeaf('b',2);
leaf[20] = fillLeaf('v',1);
leaf[21] = fillLeaf('k',1);
leaf[22] = fillLeaf('x',1);
leaf[23] = fillLeaf('j',1);
leaf[24] = fillLeaf('q',1);
leaf[25] = fillLeaf('z',1);
for(int i = 0 ; i < 26; i++){
cout << "\nthe value of leaf["<<i<<"] is the letter is "<<leaf[i].letter<< " and the frequency is " <<leaf[i].freq;
}
Node l2[13];
int j = 12;
for(int i = 0; i < 13; i++){
l2[j] = fillParent(leaf[x],leaf[x-1]);
x--;
x--;
j--;
}
for(int i = 0 ; i < 13; i++){
cout << "\nthe freq of parent["<<i<<"] is "<<l2[i].freq<< " and its right leafs letter is " << l2[i].right->letter;
}
I suspect the problem is in fillParent() function where it is assigning the pointers.