Skip to content

Instantly share code, notes, and snippets.

@Araly
Created October 12, 2018 17:05
Show Gist options
  • Save Araly/7ee31446d35ccc741f07da6367c5df48 to your computer and use it in GitHub Desktop.
Save Araly/7ee31446d35ccc741f07da6367c5df48 to your computer and use it in GitHub Desktop.
simple tree in c# for A4-IBO4
using System;
using System.Collections.Generic;
namespace adsaTree
{
class MainClass
{
public static void Main(string[] args)
{
NaryTreeNode<int> tree = new NaryTreeNode<int>(5);
Console.WriteLine(tree);
NaryTreeNode<int> node6 = tree.Add(6);
tree.Add(7);
node6.Add(8);
Console.WriteLine(tree);
Console.WriteLine(tree.Search(6));
node6.RemoveRecursive();
Console.WriteLine(tree);
}
}
class NaryTreeNode<T>
{
private T data;
private List<NaryTreeNode<T>> children;
private NaryTreeNode<T> parent;
public NaryTreeNode(T data)
{
this.data = data;
children = new List<NaryTreeNode<T>>();
this.parent = null;
}
public override string ToString()
{
string result = "(" + data.ToString();
if (children.Count != 0)
{
for (int i = 0; i < children.Count; i++)
{
result += " " + children[i].ToString();
}
}
return result + ")";
}
public NaryTreeNode<T> Search(T data)
{
NaryTreeNode<T> result = null;
if (DataEquals(data))
{
result = this;
}
else if (children.Count != 0)
{
for(int i = 0; i < children.Count; i++)
{
NaryTreeNode<T> currentResult = children[i].Search(data);
if (currentResult != null)
{
result = currentResult;
}
}
}
return result;
}
private bool DataEquals(T dataToCompareTo)
{
bool result = false;
if (dataToCompareTo is int && this.data is int)
{
if (Convert.ToInt32(dataToCompareTo) == Convert.ToInt32(this.data))
{
result = true;
}
}
return result;
}
public NaryTreeNode<T> Add(T data)
{
NaryTreeNode<T> result = null;
try
{
result = new NaryTreeNode<T>(data)
{
parent = this
};
children.Add(result);
}
catch (Exception)
{
Console.WriteLine("Add failed");
}
return result;
}
public NaryTreeNode<T> RemoveRecursive()
{
NaryTreeNode<T> result = null;
if (parent != null)
{
for (int i = 0; i < parent.children.Count; i++)
{
if (parent.children[i] == this)
{
parent.children.RemoveAt(i);
result = parent;
}
}
}
return parent;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment