Why is that sometimes a wicked person is blessed to have a righteous son?
Answer:
We cannot know the secret of why some parents are blessed with righteous children, and others not. Too many factors can be involved, and such matters are beyond our ability to fathom.
However, the Gemara does mention that "from the sons of the poor Torah shall come forth," and this demonstrates that the Torah does not pass down by inheritance, but anybody can step up and become both righteous and a Torah scholar.
Another point to note is that although parents might be wicked, there will always be righteous ancestors after going back a number of generations, and the merit of righteous ancestors cannot be ignored.