输出树结构的递归方法

Recursive methods to output Tree Structure

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

> 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);

    }
}

到目前为止,这就是我所处的位置。我只能使用递归输出列表中的 parent、children 和 children children。

> 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 + "  ");
    }
}