In the Uncapacitated Facility Location (UFL) problem, there is a fixed cost for opening a facility, and some distance matrix <i>d</i> that determines the cost of distributing commodities from any facility <i>i</i> to any consumer <i>j</i>. The problem is NP-hard in general and when <i>d</i> consists of a distance metric in a graph [7, 12]. However, for the case where the commodity transportation costs are given by path lengths in a tree, an <i>O</i>(<i>n</i><sup>2</sup>) dynamic programming algorithm was given by [4, 7]. We improve this dynamic programming algorithm by using the geometry of <i>piecewise linear functions</i> and fast merging of the binary search trees used to store these functions. We achieve the complexity bound of <i>O</i>(<i>n</i> log <i>n</i>) for the Tree Location Problem and some related problems. Our approach gives a general method for solving tree dynamic programming problems.