Created
September 30, 2017 21:04
-
-
Save SourceCode/51a682e8bc27bf33bcafdb6da9f99f0e to your computer and use it in GitHub Desktop.
A tree data structure for C# Net Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
namespace Trees1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var tree = new TreeNode("Root") | |
{ | |
new TreeNode("Cat 1") | |
{ | |
new TreeNode("Item 1"), | |
new TreeNode("Item 2"), | |
new TreeNode("Item 3"), | |
}, | |
new TreeNode("Cat 2") | |
{ | |
new TreeNode("Item 1"), | |
new TreeNode("Item 2"), | |
new TreeNode("Item 3"), | |
} | |
}; | |
} | |
} | |
public class TreeNode : IEnumerable<TreeNode> | |
{ | |
private readonly Dictionary<string, TreeNode> children = new Dictionary<string, TreeNode>(); | |
public readonly string Id; | |
public TreeNode Parent { get; set; } | |
public TreeNode(string id) | |
{ | |
this.Id = id; | |
} | |
public TreeNode GetChild(string id) | |
{ | |
return this.children[id]; | |
} | |
public void Add(TreeNode item) | |
{ | |
if (item.Parent != null) | |
{ | |
item.Parent.children.Remove(item.Id); | |
} | |
item.Parent = this; | |
this.children.Add(item.Id, item); | |
} | |
public IEnumerator<TreeNode> GetEnumerator() | |
{ | |
return this.children.Values.GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return (IEnumerator)GetEnumerator(); | |
} | |
public int Count | |
{ | |
get { return this.children.Count;} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment