Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A basic example of tree traversal using recursion in C#
// Tree traversal using recursion in C#
//
// We want to traverse the following tree, which may be arbitrarily
// deep/wide. These parameters are not known until runtime.
//
// root
// - branch1
// - leaf1
// - leaf2
// - branch2
// - branch3
// - leaf3
void Main()
{
// Entry Point
var root = CreateTestTree();
PrintNodeAndChildren(root, 0);
}
// Recursive method to print out a tree of arbitrary height/width
public void PrintNodeAndChildren(Node currentNode, int indentLevel){
var indent = new string('-', indentLevel);
Console.WriteLine("{0}{1}",indent, currentNode.Name);
foreach (Node child in currentNode.Children)
{
PrintNodeAndChildren(child, indentLevel+1);
}
}
// Just creates some data for us to mess with
Node CreateTestTree(){
var root = new Node("Root");
var branch1 = new Node("Branch 1");
var branch2 = new Node("Branch 2");
var branch3 = new Node("Branch 3");
var leaf1 = new Node("Leaf 1");
var leaf2 = new Node("Leaf 2");
var leaf3 = new Node("Leaf 3");
var leaf4 = new Node("Leaf 4");
var leaf5 = new Node("Leaf 5");
root.Children.Add(branch1);
branch1.Children.Add(leaf1);
branch1.Children.Add(leaf2);
branch1.Children.Add(leaf4);
root.Children.Add(branch2);
branch2.Children.Add(branch3);
branch2.Children.Add(leaf5);
branch3.Children.Add(leaf3);
return root;
}
// Class representing a single node on the tree
public class Node {
public Node(string name){
Children = new List<Node>();
Name = name;
}
public string Name{get;}
public IList<Node> Children{get;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.