The leaning is caused by undermining of the roots on the water side. The coconut palm (which is what we’re mostly talking about here) has a dense root network that exceeds the diameter of the tree crown by a fair amount. Tidal action or rip currents will erode the sand supporting the water-ward side of the root disk, causing the whole tree to tilt. The closer the tree is to the water’s edge, the more frequently this will happen, so you generally see the most extreme tilt right at the edge, then progressively less further away from the surf’s action, where only the occasional storm surge brings the water in. The tree compensates for the lean by readjusting its growth upward, so the tree acquires a bowed shape with the greatest incline at the bottom of the trunk.
This all serves the coconut palm quite well, by the way, because the coconut seed is buoyant and is designed (loosely speaking) to be carried by the sea to new shores. The closer the coconut falls to the water, the greater the chance that new territories will be colonized.