I think it's up to you. You can (and I have) delete your answer if you don't think it's relevant or contributes to the thread.
On the other hand, you can also modify your answer to put a short note at the top:
I understood the question to be asking ____. In light of that, I provided the answer below. However, it now appears that the question is asking ____ instead, which my post does not address.
This may be a reasonable strategy for a couple reasons. Others may have the same understanding you originally had. Your post adds to the clarity and value of the thread as a whole. Likewise, a future reader may come across the thread looking for your answer based on the same misunderstanding of the question. Moreover, someone might learn an additional fact serendipitously despite / because your answer is different.