在 C# 中遍历对象树
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/443695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Traversing a tree of objects in c#
提问by BeefTurkey
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?
我有一个由多个对象组成的树,其中每个对象都有一个名称 ( string
)、id ( int
) 以及可能是一组相同类型的子项。如何遍历整个树并打印出所有的 ID 和名称?
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.
我是编程新手,坦率地说,我无法解决这个问题,因为我不知道有多少个级别。现在我正在使用foreach
循环来直接获取根下方的父对象,但这意味着我无法获取子对象。
采纳答案by ChrisW
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
}
}
回答by Alex Fort
Well, you could always use recursion, but in a "real world" programming scenario, it can lead to bad things if you don't keep track of the depth.
好吧,您总是可以使用递归,但是在“真实世界”的编程场景中,如果您不跟踪深度,它可能会导致不好的事情。
Here's an example used for a binary tree: http://www.codeproject.com/KB/recipes/BinarySearchTree.aspx
这是用于二叉树的示例:http: //www.codeproject.com/KB/recipes/BinarySearchTree.aspx
I would google linked lists and other tree structures if you're new to the whole data structure thing. There's a wealth of knowledge to be had.
如果你对整个数据结构不熟悉,我会谷歌链接列表和其他树结构。有丰富的知识。