Just recording a simple example of Tree Traversal


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnTreeDS
{
public class Node
{
public string Name { get; set; }
public bool Visited { get; set; }
public List<Node> Children { get; set; } = new List<Node>();
}
class Program
{
/*
_ R_
/ | \
1 2 3
/ | \
4 5 6
*/
public static void TraverseFn(Node currentNode)
{
currentNode.Visited = true;
Console.WriteLine("Visited: " + currentNode.Name);
foreach (var child in currentNode.Children)
TraverseFn(child);
}
static void Main(string[] args)
{
var Root = new Node() { Name = "Root" };
var child1 = new Node() { Name = "1" };
child1.Children.Add(new Node() { Name = "4" });
child1.Children.Add(new Node() { Name = "5" });
child1.Children.Add(new Node() { Name = "6" });
Root.Children.Add(child1);
Root.Children.Add(new Node() { Name = "2" });
Root.Children.Add(new Node() { Name = "3" });
TraverseFn(Root);
Console.ReadLine();
}
}
}

view raw

main.cs

hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s