我的菜单层次结构如下所示:
Root
ProductGroups
Products
ItemTypes
Items
我避免了循环引用,因此只有父级对其子级的引用,例如ProductGroup 引用其产品。
如果我想知道某个项目属于哪个产品,我必须从根开始遍历层次结构。这会产生 5 个 for 循环:
for (MenuElement rootChild : Root.getChildren())
for(ProductGroup group : rootChild.getChildren())
for(Product product: group.getChildren())
for(ItemType itemType : product.getChildren())
for(Item item : itemType.getChildren())
if(item == searchedItem)
return product;
这是最好的方法还是您认为递归方法更好?
性能应该不会有问题:10 个产品组、10 个产品、6 个项目类型、约 30 个项目,因此递归方法不会导致严重过载。
递归的一个论据是更短的代码。这个具体案例还有更多吗?
最佳答案
如果您只是稍微频繁地调用此函数,我建议您在每个级别上包含一个父指针,或者如果您不想修改代码,请创建用于反向查找的 HashMap ,而不是使用您的任何一个解决方案。
Item->ItemType
ItemType->Product
Product->ProductGroup
您当前的解决方案始终遍历所有现有项目,这有点矫枉过正。如果您进行反向查找,您将在从 HashMap 中获取 2 次后完成,并且您的代码将更加简单,如下所示:
type = itemToTypeMap.get(item);
if (null == type); //treat error
product = typeToProductMap.get(type);
if (null == product); //treat error
return product;
关于java - 在深层层次结构中查找元素 - 迭代与递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060132/