【发布时间】:2015-03-15 11:32:00
【问题描述】:
我的菜单层次结构如下所示:
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 个 ProductGroups、10 个产品、6 个 ItemTypes、~30 个 Items,因此递归方法不会导致大的过载。
递归的一个参数是更短的代码。在这种特定情况下还有更多吗?
【问题讨论】:
-
你能显示递归版本吗?
-
recursive vs iterative 希望此链接对您有所帮助...
标签: java recursion iteration hierarchy circular-reference