简体   繁体   English

递归 function 返回 false 而不是 true

[英]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;
}

For example this is my tree:例如这是我的树:

Root
  Child 1
     GrandChild 1
  Child 2
     GrandChild 2

I pass in the function AnyChildDomainExists(root, GrandChild 2'sID) it returns false.我传入 function AnyChildDomainExists(root, GrandChild 2'sID)它返回 false。 There is a small issue in the function but I am unable to figure it out. function 中有一个小问题,但我无法弄清楚。

private bool AnyChildDomainExists(Domain parentDomain, int childDomainID)
{
    if (parentDomain.DomainID == childDomainID)
        return true;

    return parentDomain.Domains.Any(domain => AnyChildDomainExists(domain, childDomainID));

}

Check if any of the child domain Ids match, using LINQ Any .使用 LINQ Any检查是否有任何子域 ID 匹配。

Another way to do this is to only return from the inner loop if the result is true .另一种方法是仅在结果为true时从内部循环返回。 As it stands, you're returning a value on the first iteration of child domains, which is not what you want.就目前而言,您在子域的第一次迭代中返回一个值,这不是您想要的。

For example:例如:

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;
}

The way the loop is written, it returns the result from the first leaf node immediately and propagates it all the way to the top.循环的编写方式,它立即从第一个叶节点返回结果并将其一直传播到顶部。 This means that if GrandChild 2 returns false .这意味着如果GrandChild 2返回false

One way to fix this is to OR the results of all children in the loop, eg:解决此问题的一种方法是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;
}

This code will return true for node 22 (GrandChild 2):此代码将为节点 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM