You are making node to point itself in first code, So when you call printCodes it will never end because of self loop.
node* t=new node('$',0);
t->p.first= t->l->p.first + t->r->p.first;
this snippet from your code. Say t is pointing to some address X. You are pushing the same address into priority_queue repeatedly. After some iterations X will point itself(X->l = X and X->r = X) but in code 2 you are creating new node at every step (no node will point itself)that’s why it’s working fine.