Traversing a tree of objects in c#

梦想的初衷 提交于 2019-11-26 18:02:54

问题


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?

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.


回答1:


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
  }
}



回答2:


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

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.



来源:https://stackoverflow.com/questions/443695/traversing-a-tree-of-objects-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!