This paper designs energy-efficient trajectories for unmanned aerial vehicles (UAVs) harvesting data sequentially from distributed ground nodes. We propose a novel optimization framework for path planning, based on dynamic programming. We develop an optimum backward-forward algorithm that jointly optimizes the hovering locations for each ground node, and the visiting order to those locations. Our algorithm minimizes the total energy consumption of the UAV over its trajectory. Our framework is compatible with various probabilistic wireless communication channel models, and can also be applied to different cost functions, including minimising the total flying time, and allowing for bi-directional communications. We also develop a lower complexity algorithm that approximates the optimum UAV trajectory by decomposing the original problem into two sub-problems, and iterating back and forth between the two. This alternating algorithm has polynomial time complexity, and we show that it produces a near-optimum UAV trajectory, with as little deviation as 5% to 15% from the average energy consumption of the optimum algorithm.