我有一个由多个对象组成的树,其中每个对象都有一个名称(string)、id(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 the root, but 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 } }