Tree Recovery by Dynamic Programming