c# - 集合中的递归函数

标签 c# function recursion

我正在使用 C# 和 List 集合并加载值。完成后,我将尝试递归读取它们,但有些方法我无法实现。

以下是我的主要代码。

    private static void Main(string[] args)
            {
                var node = new Node
                    {
                        Name = "N1",
                        Nodes =
                            new List<Node>
                                {
                                    new Node { Name = "N1a" },
                                    new Node { Name = "N1b", Nodes = new List<Node> { new Node { Name = "N1B1" } } },
                                    new Node
                                        {
                                            Name = "N1c",
                                            Nodes =
                                                new List<Node> { new Node { Name = "N1C1", Nodes = new List<Node> {new Node{Name = "N1C1A"} } } }
                                        }
                                }
                    };
                GetNodes( node );
                Console.ReadLine();
            }

 public class Node
        {
            public string Name { get; set; }

            public IList<Node> Nodes { get; set; }
        }

接下来是函数调用

public static IEnumerable<Node> GetNodes(Node node)
        {
            if (node == null)
            {
                return null;
            }

            Console.WriteLine(node.Name);

            foreach (var n in node.Nodes)
            {
                return GetNodes(n);
            }

            return null;
        }
    }  

谁能帮我修复递归函数?

最佳答案

如果只想打印所有节点的名称,

public static void GetNodes(Node node)
{
    if (node == null)
    {
        return;
    }
    Console.WriteLine(node.Name);
    foreach (var n in node.Nodes)
    {
        GetNodes(n);
    }
}

如果你想把树弄平,

public static IEnumerable<Node> GetNodes(Node node)
{
    if (node == null)
    {
        yield break;
    }
    yield return node;
    foreach (var n in node.Nodes)
    {
        foreach(var innerN in GetNodes(n))
        {
            yield return innerN;
        }
    }
}

关于c# - 集合中的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620260/

相关文章:

c# - 在 Window 服务中处理 WebApp.Start 实例的正确位置?

c# - 为什么 IPAddress 有时会抛出 ArgumentOutOfRangeException?

c# - 将 Linq 与二维数组一起使用,找不到选择

javascript - 为什么 Crockford 使用这种格式来编写 JSON.parse 函数?

c - 尝试使用递归反向打印链表数据时出现段错误

c# - 在 Entity Framework 中,您应该在哪里检查用户是否有权获取或设置 DbSet/DbContext 中的数据?

python - 如何将特定参数传递给python中的装饰器

python - 如何在这种情况下正确使用嵌套列表

java - 为什么java更擅长处理递归?

java - java - 如何在不使用循环和递归的情况下打印数组