Recursion with yield return elements order in tree

前端 未结 3 585
挽巷
挽巷 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:46

    Yes it's possible, just put the yield return before the foreach. You are thinking of the behaviour of a normal return statement.

    0 讨论(0)
  • 2021-01-02 06:49

    Have you tried something like:

    private IEnumerable<Node> 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.

    0 讨论(0)
  • You need to explicitly iterate + yield return the nodes of children of each node ala:

            public IEnumerable<int> preOrder(Node root)
            {
                if (root == null)
                    yield break;
    
                yield return root.val;
    
                if (root.left != null)
                    foreach (int i in preOrder(root.left))
                        yield return i;
    
                if (root.right != null)
                    foreach (int i in preOrder(root.right))
                        yield return i;
            }
    
    0 讨论(0)
提交回复
热议问题