I have a recursive function that returns all subtree nodes, given the starting root node.
private IEnumerable getAllNodesRecursively(Node subnode
Yes it's possible, just put the yield return before the foreach. You are thinking of the behaviour of a normal return statement.
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.
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;
}