"He reckons the fathers' transgression to the sons' account, up to the third and fourth generations" [Shelach 14:18]
In explaining how children can be punished for the sins of their parents, R' Berechiah HaNakdan recounts the following parable:
A hungry wolf met a fox and desired to devour it.
"Why would you want to devour me?" asked the sly fox. "I am thin and have few bones... go and devour a fat-fleshed human, and you will enjoy the feast."
"I cannot devour a human" replied the wolf, "as the verse states "Of every beast I will demand it" [Bereishis 9:5] - [this verse warns beasts against killing people - see Rashi there]
The fox cackled and said "You have nothing to fear, for it is not you who will receive the punishment, but your children, as the verse says "He reckons the fathers' transgression to the sons' account."
The wolf was persuaded by the fox, and it began to search for a human. On the way, it fell into a trap laid by hunters. The wolf began yelling for help. When the fox heard the calls of the wolf, it carefully approached the wolf.
"You liar!" screamed the wolf. "Did you not say that only my children would get punished for my sins?"
"Fool that you are" replied the fox, "You are also not getting punished on account of your own sins, but for the sins of your fathers."
"How could that be?" screamed the wolf....."Why would I suffer for what others have done?"
"And why did you set out to devour humans?" queried the fox. "Was it not because you were counting on the fact that it would be your children who would suffer for your sins? Since you felt it was fair that your children bear your sins, it is only fitting that you bear your fathers' sins!"
A child, concluded R' Berechiah, is only punished for his father's sins if he is guilty of the same sins. This is because an individual's punishment is meted out measure for measure. When someone emulates the sinful ways of his father, without concern that his children will receive punishment on account of his sins, he too gets punished for the sins of his fathers.
If this is true of the negative, how much more so is it true of the positive: when a righteous son follows in the ways of a righteous father, he will certainly be rewarded for the good deeds of his father!
Source: Rabbi Yisrael Bronstein