Hello people.
I'm trying to figure out how to implement a function in a tree node which returns all its descendant leaves (whether direct or indirect). However, I don't want to pass a container in which the leaf nodes will be put recursively (the tree could be huge), instead I'd like to use a generator to iterate through the tree. I've tried a few approaches but none of them worked so far. This one is the closest I've come to a possible solution:
public interface ITreeNode
{
IEnumerable<ITreeNode> EnumerateLeaves();
}
class Leaf : ITreeNode
{
public IEnumerable<ITreeNode> EnumerateLeaves()
{
throw new NotImplementedException();
}
}
class Branch : ITreeNode
{
private List<ITreeNode> m_treeNodes = new List<ITreeNode>();
public IEnumerable<ITreeNode> EnumerateLeaves()
{
foreach( var node in m_treeNodes )
{
if( node is Leaf )
yield return node;
else
node.EnumerateLeaves();
}
}
}
But this is not working either. What am I doing wrong? Seems like calling .EnumerateLeaves recursively won't work if there's a yield statement in the same function.
Any help would be very much appreciated. Thanks in advance.
Edit: I forgot to mention that a branch can have either leaves or branches as children, hence the recursion.