Recursion with yield return elements order in tree

前端 未结 3 584
挽巷
挽巷 2021-01-02 06:24

I have a recursive function that returns all subtree nodes, given the starting root node.

private IEnumerable getAllNodesRecursively(Node subnode         


        
3条回答
  •  醉梦人生
    2021-01-02 06:49

    Have you tried something like:

    private IEnumerable getAllNodesRecursively(Node subnode) 
    { 
        // Return the parent before its children
        yield return subnode; 
    
        foreach (Node node in subnode.Nodes) 
        {
            foreach(Node n in getAllNodesRecursively(node))
            {
                yield return n;
            }
        }
    } 
    

    Your implementation is calling getAllNodesRecursively recursively, but ignoring its return value.

提交回复
热议问题