The problem is with this code:
parent.left = &a;
parent.right = &b;
This is getting pointers to local variables, which will be reinitialized next time around the loop. CharCountNode
will eventually try to delete
these objects, but they haven't been allocated by new.
You need to make left
and right
point to objects allocated on the heap, as that is what CharCountNode
is expecting. Something like:
parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);