Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a simple, high performance Tree Data Structure in c#

Tags:

c#

tree

I need to create a product catalog, in tree type.

every tree node presents by a ID(string), the functions on the tree data only 2:

  1. getChild(string ID), give a ID, get children (no need include childrens' children), if ID is null, get all root nodes
  2. getParent(string ID), return parent ID if have, or null if is root

Since once the tree decided, will not change, so I think put all code in static will be best. So I start to try use Dictionary

"id": {parent:ID, child:[id2, id3, id4....]} 

Since theres about 1000+ catalog, I found I quickly mess myself up, lots of mistake in the static data, and make final result on usable. Also, now I only wrote dozens and the code is looking like mess.

Please advice a way create this simple catalog tree with high performance. Thanks

like image 232
Eric Yin Avatar asked Mar 25 '12 12:03

Eric Yin


People also ask

What is simple tree in data structure?

A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value and a list of references to other nodes (the “children”). This data structure is a specialized method to organize and store data in the computer to be used more effectively.

Which is the most efficient data structure for creation of tree?

Array is a good static data structure that can be accessed randomly and is fairly easy to implement. Linked Lists on the other hand is dynamic and is ideal for application that requires frequent operations such as add, delete, and update.

What is the best use of tree in data structure?

Store hierarchical data, like folder structure, organization structure, XML/HTML data. Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows finding closest item. Heap is a tree data structure which is implemented using arrays and used to implement priority queues.

What is a tree in C programming?

A tree includes multiple nodes. In C, we call it a Binary Tree. A tree is referred to as a finite and non-empty set of elements in mathematical terminology. 1. Root:- A root is a node without a parent. In the above image, 50 is the root node. 2. Siblings:- Siblings mean that nodes which have the same parent node.

What is syntax tree data structure in C?

It is a type of tree data structure that helps in maintaining a sorted stream of data. Tree data structures are used to store the hierarchical data, which means data arranged in the form of order. The syntax tree represents the structure of the program’s source code, which is used in compilers.

What is a tree data structure?

We can also say that tree data structure has roots, branches, and leaves connected with one another. A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value, a list of references to nodes (the “children”).

What is binary tree in C?

Introduction to Binary Tree Program in C Binary tree program in C is a nonlinear data structure used for data search and organization. Binary tree is comprised of nodes, and these nodes each being a data component, have left and right child nodes.


1 Answers

Just make a class out of it.

UPDATED:

class TreeNode : IEnumerable<TreeNode> {     private readonly Dictionary<string, TreeNode> _children =                                         new Dictionary<string, TreeNode>();      public readonly string ID;     public TreeNode Parent { get; private 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 this.GetEnumerator();     }      public int Count     {         get { return this._children.Count; }     } } 

Usage will be fairly simple to statically define:

var tree = new TreeNode("Root")                {                    new TreeNode("Category 1")                        {                            new TreeNode("Item 1"),                            new TreeNode("Item 2"),                            new TreeNode("Item 3"),                        },                    new TreeNode("Category 2")                        {                            new TreeNode("Item 1"),                            new TreeNode("Item 2"),                            new TreeNode("Item 3"),                            new TreeNode("Item 4"),                        }                }; 

Edit

Some more functionality for even easier creation...

public static TreeNode BuildTree(string tree) {     var lines = tree.Split(new[] { Environment.NewLine },                            StringSplitOptions.RemoveEmptyEntries);      var result = new TreeNode("TreeRoot");     var list = new List<TreeNode> { result };      foreach (var line in lines)     {         var trimmedLine = line.Trim();         var indent = line.Length - trimmedLine.Length;          var child = new TreeNode(trimmedLine);         list[indent].Add(child);          if (indent + 1 < list.Count)         {             list[indent + 1] = child;         }         else         {             list.Add(child);         }     }      return result; }  public static string BuildString(TreeNode tree) {     var sb = new StringBuilder();      BuildString(sb, tree, 0);      return sb.ToString(); }  private static void BuildString(StringBuilder sb, TreeNode node, int depth) {     sb.AppendLine(node.ID.PadLeft(node.ID.Length + depth));      foreach (var child in node)     {         BuildString(sb, child, depth + 1);     } } 


Usage:

var tree = TreeNode.BuildTree(@" Cat1  Sub1   Item1   Item2   Item3  Sub2   Item1   Item2 Cat2  Sub1  Sub2   Item1   Item2  Sub3   Item1 Cat3 Cat4"); 
like image 120
SimpleVar Avatar answered Sep 19 '22 13:09

SimpleVar