Refactoring to make tree generic and some optimisations