You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Trees/Generic.cs

76 lines
2.2 KiB

using System.Collections.Generic;
6 years ago
using System.Linq;
namespace ZeroLevel.Services.Trees
{
public class GNode<T>
6 years ago
{
public string Id { get; set; }
public T Value { get; set; }
public readonly Dictionary<string, GNode<T>> Nodes = new Dictionary<string, GNode<T>>();
6 years ago
public void Add(string[] path, int index, T value)
6 years ago
{
if (path.Length > index)
6 years ago
{
if (false == Nodes.ContainsKey(path[index]))
6 years ago
{
Nodes[path[index]] = new GNode<T>();
}
if (path.Length == (index + 1))
{
Nodes[path[index]].Value = value;
}
else
{
Nodes[path[index]].Add(path, index + 1, value);
6 years ago
}
}
}
}
6 years ago
public class GTree<T>
{
private readonly Dictionary<string, GNode<T>> _rootNodes = new Dictionary<string, GNode<T>>();
public IEnumerable<GNode<T>> RootNodes => _rootNodes.Values.ToArray();
6 years ago
public void Add(string[] path, T value)
6 years ago
{
if (path.Length > 0)
6 years ago
{
if (false == _rootNodes.ContainsKey(path[0]))
{
_rootNodes[path[0]] = new GNode<T>();
}
if (path.Length == 1)
{
_rootNodes[path[0]].Value = value;
}
else
{
_rootNodes[path[0]].Add(path, 1, value);
}
6 years ago
}
}
5 years ago
/// <summary>
/// traversing a tree in width from left to right
/// </summary>
public IEnumerable<GNode<T>> Plain()
{
var queue = new Queue<GNode<T>>();
foreach (var r in _rootNodes) {
queue.Enqueue(r.Value);
}
while (queue.Count > 0)
{
var current = queue.Dequeue();
yield return current;
foreach (var r in current.Nodes)
{
queue.Enqueue(r.Value);
}
}
}
6 years ago
}
}

Powered by TurnKey Linux.