Why doesn't this recursion work in C #?

public static bool AllNodesChecked(TreeNodeCollection nodes)        
{
    foreach (TreeNode node in nodes)
    {
        if (!node.Checked)
        {
            return false;
        }
        AllNodesChecked(node.Nodes);
    }
    return true;
}

Test tree

A1(checked) -> B1(unchecked)
A2(checked)
A3(checked)

but it does not return when it clicks node B1.

EDIT: Thanks for helping my tired brain. Recursion should only be undertaken at the beginning of the day after a cold shower.

+3
source share
6 answers

You ignore the return value AllNodesCheckedin the recursive call:

public static bool AllNodesChecked(TreeNodeCollection nodes)        
{
    foreach (TreeNode node in nodes)
        if (!node.Checked || !AllNodesChecked(node.Nodes))
           return false;
    return true;
}

The statement returnreturns only the current method in the call stack to the immediate caller. It does not suddenly return from all other calls above in the call stack.

+20
source

Edit:

AllNodesChecked(node.Nodes); 

To:

if(!AllNodesChecked(node.Nodes))
    return false;
+8
source

. , , ( , ) . - :

static IEnumerable<Node> AllNodes(this Node node)
{
    var stack = new Stack<Node>();
    stack.Push(node);
    while(stack.Count > 0)
    {
        var current = stack.Pop();
        yield return current;
        foreach(var child in current.Nodes)
            stack.Push(child);
    }
}

:

bool allChecked = root.AllNodes().All(x=>x.Checked);

, .

+7
source

You do not evaluate the result of a recursive call to test child nodes.

+3
source

Try the following:

public static bool AllNodesChecked(TreeNodeCollection nodes)         
{ 
    foreach (TreeNode node in nodes) 
    { 
        if (node.Checked == false || !AllNodesChecked(node.Nodes)) 
        { 
            return false; 
        } 
    } 
    return true; 
} 
+2
source

I have to add my two cents .... Learn functional programming IMHO.

public static bool AllNodesChecked(TreeNodeCollection nodes)  
{
    return nodes.All(i => i.Checked && AllNodesChecked(i.Nodes));
}
-1
source

Source: https://habr.com/ru/post/1732370/


All Articles