A dynamic programming method is elaborated, enabling the characterization of trees with a given number of pendent vertices, for which a vertex-degree-based invariant (“topological index”) achieves its extremal value. The method is applied to the chemically interesting and earlier much studied such invariants: the first and second Zagreb index, and the atom–bond connectivity index.