Simple implementation of generic TREE in C#

using System;
using System.Collections.Generic;

public class Tree<T>
{
	public Tree(
		T value,
		params Tree<T>[] children)
	{
		this.Value = value;

		this.Children = new List<Tree<T>>();
		foreach (var child in children)
		{
			this.Children.Add(child);
		}
	}
		
	public T Value { get; private set; }

	public ICollection<Tree<T>> Children { get; private set; }

	public void EachTree(Action<T> action)
	{
		action(this.Value);

		foreach (var child in this.Children)
		{
			child.EachTree(action);
		}
	}

	public void PrintTree(int indent = 0)
	{
		Console.WriteLine(new string(' ', indent * 2) + this.Value);
		indent++;
		foreach (var child in this.Children)
		{
			child.PrintTree(indent);
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *