Issue with recursive tree traversal in c#
我具有以下格式的树结构数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | H1 H1 - 1 H1 - 1 - 1 H1 - 1 - 1 - 1 H1 - 1 - 1 - 1 -1 H1 - 1 - 1 - 1 -1 - 1 H1 - 1 - 2 H1 - 1 - 3 H1 - 2 H1 - 2 - 1 H1 - 2 - 2 H2 H3 H3 - 1 H3 - 1 - 1 H3 - 1 - 1 - 1 H3 - 1 - 1 - 1 - 1 H3 - 1 - 1 - 2 H3 - 1 - 2 H3 - 1 - 3 H3 - 2 |
我必须通过传递子项的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public bool CheckIfChildItemExists(Item parentItem, long childItemId) { var isChildExisting = false; foreach (Item item in parentItem.Children) { if (item == context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault() || item.Children.Contains(context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault())) { isChildExisting = true; return isChildExisting; } else { return CheckIfChildItemExists(item, childItemId); } } return isChildExisting; } |
使用上述方法:
-
根项目
H1, H2, H3 是可访问的。 -
可以访问
H1 的所有分支(H1 -1 ,H1 - 1 - 1 ,H1 - 1 - 1 -1 等)。 -
H1 - 2 - 1 和H1 - 2 - 2 是不可访问的,它们没有被遍历。但是可以访问其父项H1 - 2 。 -
H3 的所有子项均不可访问。
我的方法在做什么错?
您要早点回来。实际上,您要做的是从根到叶最多签入一个分支,但是您从不签到其他分支。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public bool CheckIfChildItemExists(Item parentItem, long childItemId) { foreach (Item item in parentItem.Children) { if (item == context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault() || item.Children.Contains(context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault())) { return true; } else { var childItemExists = CheckIfChildItemExists(item, childItemId); if(childItemExists) return true; // else continue search in other children } } return isChildExisting; } |
我不确定您在
1 2 3 4 5 6 7 8 9 10 | public bool CheckIfChildItemExists(Item parentItem, long childItemId) { if(parentItem.ItemID == childItemId && parentItem.IsActive) return true; foreach (Item item in parentItem.Children) { var childItemExists = CheckIfChildItemExists(item, childItemId); if(childItemExists) return true; // else continue search in } return false; } |
在