Refactor tree search