[英]Recursive methods to output Tree Structure
我有一个C#程序,该程序利用控制台在动物园中执行操作。 目前,我被要求使用私人静态方法来展示我在动物园里饲养的动物的孩子。 然后是他们的孩子的孩子,等等...我有另一个方法,当在控制台中键入该方法时,首先找到特定的动物,然后使用传入的动物调用另一个静态WalkTree方法。 WalkTree方法将执行递归方法,并将找到的子图之类的树输出到控制台。 每个级别都需要像这样踢出才能显示“家谱”。
> 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)
在此先感谢您,如果有任何疑问,请通知我!
我想你已经快到了。 需要进行两项更改:
WalkTree
每个递归调用都使用相同的前缀。 根据您自己的描述,您想为每个级别添加两个空格,因此需要将此空格附加到当前前缀。 因此,进行以下两个更改:
private static void WalkTree(Animal animal, string prefix)
{
Console.WriteLine(prefix + animal.ToString());
foreach (Animal a in animal.Children)
{
WalkTree(a, prefix + " ");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.