codeStr.append modifies codeStr . So, you correctly pass codeStr + "1" first recursive call, but codeStr + "10" to the second. As a result, all occurrences of "0" are added by an additional "1".
Try
createCode(root->getLeftChild(), codeStr + "1",table); createCode(root->getRightChild(), codeStr + "0",table);
source share