I checked Robert Hendrickson's Encyclopedia of Word and Phrase Origins, and he says "the superstition is an old one and has many possible explanations, none sure. It may be of pagan origin, deriving from the practice of rapping on trees to ask protection from friendly spirits who were believed to reside inside. Or it could be a Christian superstision similar to touching wodden cricifixes or rosary beads."