refactor tree logic