I am new to C++ and I am trying to implement Huffman Codes in it. To do so I had to implement a tree-like structure in it which required me to implement pointers in a structure. But the problem that I am facing is that every time I allocate a new value to a variable it is getting the same address and the tree that I am trying to implement is becoming self-referential at the topmost element which is preventing me from traversing it.
Here is my code -
#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
struct node{
int freq;
string symbol;
node *left = nullptr, *right=nullptr;
string huff;
};
vector<node> nodes;
vector<node> nodeSort(vector<node> arr, int s){
for(int x=0;x<s;x++){
for(int y=x+1;y<s;y++){
if(arr[x].freq>arr[y].freq){
node temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
return arr;
}
void printHuff(node Node, string val=""){
string newval = val+Node.huff;
if(Node.left!=nullptr){
printHuff(*Node.left,newval);
}
if(Node.right!=nullptr){
cout<<2;
printHuff(*Node.right,newval);
}
if(Node.left==nullptr and Node.right==nullptr){
cout<<Node.symbol<<" -> "<<newval;
}
}
int main(){
char symbols[] = {'A','B','C','D'};
int freq[] = {5,1,6,3};
for(int x=0;x<4;x++){
node temp;
temp.freq = freq[x];
temp.symbol = symbols[x];
temp.huff = "";
nodes.push_back(temp);
}
while(nodes.size()>1){
nodes = nodeSort(nodes,nodes.size());
node left = nodes[0];
node right = nodes[1];
node temp;
left.huff += "0";
right.huff += "1";
temp.freq = left.freq + right.freq;
temp.symbol = left.symbol + right.symbol;
temp.left = &left;
temp.right = &right;
nodes.erase(nodes.begin());
nodes.erase(nodes.begin());
nodes.push_back(temp);
}
node a = nodes[0];
cout<<a.left->symbol<<endl;
cout<<a.right->symbol<<endl;
cout<<a.right->left->symbol<<endl;
cout<<a.right->right->symbol<<endl;
// printHuff(nodes[0]);
return 0;
}
Here is the expected Huffman Tree -
Here is the output -
C
BDA
C
BDA
Which is definitely wrong. But I am unable to find out what referencing am I doing wrong? I am new to C++, although I have implemented the same algorithm in Python, I am unable to understand what is going wrong here.