Refactor buildWordTree