【发布时间】:2011-05-24 23:59:47
【问题描述】:
这就是我所拥有的:一棵具有任意层数的树。我需要一种方法来对每个级别的每个级别的所有节点进行排名。如果不清楚,假设我的第一个级别是世界。我的第二个层次是大陆。我的第三个层次是国家。我的第四层是城市。每个国家都有一个城市列表,按人口顺序排列。每个大陆都有一个按人口排列的国家列表。每个大陆也有一个按人口排名的城市列表。等等。
我想象的算法是非常简单的递归,但我不确定跟踪这些列表的最佳数据结构是什么。每个级别不知道它有多少个子级别,所以我不能声明任意数量的列表。
有什么想法吗?
这里有一些示例代码:
public void calcStats()
{
initWorldRanks();//clears ranks for the world
for(Entity continent:theWorld.getChildren())
{
initContinentRanks();//clears ranks for the continent
for(Entity country:continent.getChildren())
{
initCountryRanks();//clears ranks for the country
for(Entity city:country.getChildren())
{
//Assume that add preserves sorted order. Sorting is easy. The tricky part is that each entity needs to be added to its ancestors. I don't want to have fixed data structures
worldCityRanks.add(city);
continentCityRanks.add(city);
countryCityRanks.add(city);
}
worldCountryRanks.add(country);
continentCountryRanks.add(country);
}
worldContinentRanks.add(continent);
}
一切都正确排名,但这将我限制在明确的 4 级结构中。
【问题讨论】:
标签: java algorithm sorting data-structures collections