问题描述
我有个树由多个对象,其中每个对象具有一个名称(字符串),编号(int)和可能的子女的阵列,其是相同类型的。我该如何去通过整个树,并打印出所有的ID和姓名?
I have a tree that consists of several objects where each object has a name (string), id (int) and possibly an array of children, that are of the same type. How do I go through the entire tree and print out all of the ids and names?
我是新来的编程坦率地说,我有麻烦缠绕我的头围绕这一点,因为我不知道有多少水平有。现在,我使用foreach循环来获取父对象正下方腐烂,把这意味着我不能让孩子。
I'm new to programming and frankly, I'm having trouble wrapping my head around this because I don't know how many levels there are. Right now I'm using a foreach loop to fetch the parent objects directly below rot, put this means I cannot get the children.
推荐答案
这是算法,使用递归是这样的:
An algorithm which uses recursion goes like this:
printNode(Node node)
{
printTitle(node.title)
foreach (Node child in node.children)
{
printNode(child); //<-- recursive
}
}
下面是一个版本,这也将跟踪如何深度嵌套的递归(即我们是否要打印的根的孩子,大儿,大 - 大 - 儿童,等等。):
Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):
printRoot(Node node)
{
printNode(node, 0);
}
printNode(Node node, int level)
{
printTitle(node.title)
foreach (Node child in node.children)
{
printNode(child, level + 1); //<-- recursive
}
}
这篇关于遍历对象的树在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!