我有这个递归查找以获取销售代表所属的地区列表 - 问题是我遇到了“太多CPU时间”调控器限制。关于如何重新编写它以使它不这样做的任何建议?
public List<string> getHeirarchy() {
List<Territory> territories = [SELECT Id, Custom_External_TerritoryId__c, ExternalParentTerritoryId__c FROM Territory];
return getParentAndChildren(getTerritory(), territories);
}
public Set<string> getChildren(string parent, List<Territory> territories) {
Set<string> subset = new Set<string>();
for(Territory t : territories) {
if (t.ExternalParentTerritoryId__c == 'US-'+parent) {
subset.add(t.Custom_External_TerritoryId__c.SUBSTRING(3));
}
}
return subset;
}
public List<string> getParentAndChildren(string parent, List<Territory> territories) {
Set<string> collection = new Set<string>();
Set<string> children = getChildren(parent, territories);
if(children.size() > 0) {
for(string child : children) {
collection.addAll(getParentAndChildren(child, territories));
}
}
collection.add(parent);
List<string> sorted = new List<string>(collection);
//sorted.sort();
return sorted;
}