[英]Recursive function returns false instead of true
private bool AnyChildDomainExists(Domain parentDomain, int childDomainID)
{
if (parentDomain.DomainID == childDomainID)
return true;
foreach(Domain domain in parentDomain.Domains)
{
return AnyChildDomainExists(domain, childDomainID);
}
return false;
}
例如這是我的樹:
Root
Child 1
GrandChild 1
Child 2
GrandChild 2
我傳入 function AnyChildDomainExists(root, GrandChild 2'sID)
它返回 false。 function 中有一個小問題,但我無法弄清楚。
private bool AnyChildDomainExists(Domain parentDomain, int childDomainID)
{
if (parentDomain.DomainID == childDomainID)
return true;
return parentDomain.Domains.Any(domain => AnyChildDomainExists(domain, childDomainID));
}
使用 LINQ Any檢查是否有任何子域 ID 匹配。
另一種方法是僅在結果為true
時從內部循環返回。 就目前而言,您在子域的第一次迭代中返回一個值,這不是您想要的。
例如:
private bool AnyChildDomainExists(Domain parentDomain, int childDomainID)
{
if (parentDomain.DomainID == childDomainID) return true;
foreach(Domain domain in parentDomain.Domains)
{
if (AnyChildDomainExists(domain, childDomainID)) return true;
}
return false;
}
循環的編寫方式,它立即從第一個葉節點返回結果並將其一直傳播到頂部。 這意味着如果GrandChild 2
返回false
。
解決此問題的一種方法是OR
循環中所有子項的結果,例如:
private bool AnyChildDomainExists(Domain parentDomain, int childDomainID)
{
if (parentDomain.DomainID == childDomainID)
return true;
bool result=false;
foreach(Domain domain in parentDomain.Domains)
{
result|=AnyChildDomainExists(domain, childDomainID);
}
return result;
}
此代碼將為節點 22(GrandChild 2)返回true
:
var tree=new Domain(0,new[]{
new Domain(1,new[]{
new Domain(11,new Domain[0])
}),
new Domain(2,new[]{
new Domain(22,new Domain[0])
})
});
var found=AnyChildDomainExists(tree,22);
Debug.Assert(found);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.