recursive version of flatten tree