Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a tree of objects in c#

Tags:

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.

like image 732
BeefTurkey Avatar asked Jan 14 '09 16:01

BeefTurkey


People also ask

What is tree traversal in C?

Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot random access a node in a tree. There are three ways which we use to traverse a tree − In-order Traversal.


1 Answers

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   } } 
like image 149
ChrisW Avatar answered Oct 06 '22 01:10

ChrisW