递归与yield返回树中的元素顺序
我有一个递归函数,在给定起始根节点的情况下返回所有子树节点。
private IEnumerable<Node> getAllNodesRecursively(Node subnode)
{
foreach (Node node in subnode.Nodes)
getAllNodesRecursively(node);
yield return subnode;
}
对于以下树结构:
A
|
+--B
|
+--C
| |
| +--D
|
+--E
当我尝试这样迭代时:
foreach (Node n in getAllNodesRecursively(a))
{
Console.WriteLine(n);
}
该函数仅返回 A 值。
我希望将yield-return与递归结合使用并检索预购中的元素(本例中为A、B、C、D、E)。
(如果我将收益返回放在 foreach 之前,则 foreach 将永远不会发生)。
这可能吗?
I have a recursive function that returns all subtree nodes, given the starting root node.
private IEnumerable<Node> getAllNodesRecursively(Node subnode)
{
foreach (Node node in subnode.Nodes)
getAllNodesRecursively(node);
yield return subnode;
}
For the following tree structure:
A
|
+--B
|
+--C
| |
| +--D
|
+--E
When I try to iterate as such:
foreach (Node n in getAllNodesRecursively(a))
{
Console.WriteLine(n);
}
the function returns the only the A value.
I wish to use yield-return with recursion and retrieve elements in the Preorder (A, B, C, D, E in this example).
(If I put the yield return before the foreach, the foreach would never happen).
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过类似的操作:
您的实现正在递归调用
getAllNodesRecursively
,但忽略其返回值。Have you tried something like:
Your implementation is calling
getAllNodesRecursively
recursively, but ignoring its return value.是的,这是可能的,只需将
yield return
放在foreach
之前即可。您正在考虑正常return
语句的行为。Yes it's possible, just put the
yield return
before theforeach
. You are thinking of the behaviour of a normalreturn
statement.您需要显式迭代+yield返回每个节点ala的子节点:
You need to explicitly iterate + yield return the nodes of children of each node ala: