Refactor flatTree