gpt4 book ai didi

c# - 输出树结构的递归方法

转载 作者:行者123 更新时间:2023-11-30 23:26:09 25 4
gpt4 key购买 nike

我有一个 C# 程序,它利用控制台在动物园中执行操作。目前我被要求使用私有(private)静态方法来展示我在动物园里的动物的 child 。然后他们的 child 的 child 等等......我有另一种方法,当在控制台中输入时首先找到特定的动物,然后用传入的动物调用另一个静态 WalkTree 方法。 WalkTree 方法是执行递归方法并将找到的 child 的树状图输出到控制台。每个级别都需要像这样被踢出以显示“家谱”。

> show children Bella
Bella: Dingo (10, 40.2)
Coco: Dingo (7, 38.3)
Brutus: Dingo (3, 36)
Maggie: Dingo (7, 34.8)
Toby: Dingo (4, 42.5)
Steve: Dingo (4, 41.1)
Lucy: Dingo (7, 36.5)
Ted: Dingo (7, 39.7)

树的每一层都应该在前缀中添加两个空格,如上例。

/// Shows a list of children of the animals in the zoo.
private static void ShowChildren(Zoo zoo, string name)
{
// Find the animal with the passed-in name.
Animal animal = zoo.FindAnimal(name);

// Then call the WalkTree method and pass in the animal and an empty string.
WalkTree(animal, string.Empty);
}

/// Walks down a tree of parents and children in the zoo.
private static void WalkTree(Animal animal, string prefix)
{
prefix = " ";
Console.WriteLine(animal);
foreach (Animal a in animal.Children)
{
WalkTree(a, prefix);

}
}

到目前为止,这就是我所处的位置。我只能用递归的方式把父子子孙子级输出到一个列表中。

> show children Bella
Bella: Dingo (10, 40.2)
Coco: Dingo (7, 38.3)
Brutus: Dingo (3, 36)
Maggie: Dingo (7, 34.8)
Toby: Dingo (4, 42.5)
Steve: Dingo (4, 41.1)
Lucy: Dingo (7, 36.5)
Ted: Dingo (7, 39.7)

提前致谢,如果你们有任何问题,请告诉我!

最佳答案

我想你快到了。需要进行两项更改:

  1. 您在编写控制台的内容中没有使用前缀。您需要为每只动物的输出字符串添加前缀。
  2. 您对 WalkTree 的每次递归调用都使用相同的前缀。根据您自己的描述,您希望为每个级别添加两个空格,因此您需要将其附加到当前前缀。

因此,进行以下两项更改:

private static void WalkTree(Animal animal, string prefix)
{
Console.WriteLine(prefix + animal.ToString());
foreach (Animal a in animal.Children)
{
WalkTree(a, prefix + " ");
}
}

关于c# - 输出树结构的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com