In cricket, if a throw to the stumps hits the wicketkeeper's helmet, will penalty runs be awarded even if the throw wasn't traveling to the boundary?
Yes. Law 41.3 states:
If a protective helmet belonging to the fielding side is on the ground within the field of play, and the ball while in play strikes it, the ball shall become dead and [...] 5 penalty runs shall then be awarded to the batting side
There is no mention in the Laws as to where the ball may or may not be travelling at the time the helmet is struck.