I have a data structure that looks like this:
public class Node
{
public string Code { get; set; }
public string Description { get; set; }
...
public List<Node> Children { get; set; }
}
I want to write a method that will return a specific node, given the specified Code. Normally I would just do a recursive walk through the hierarchy to find the node, but I’m concerned about performance. There will be several thousand nodes in the hierarchy, and this method will be called many, many times.
How do I structure this to make it faster? Can I use an existing data structure that perhaps performs a binary search on Code while retaining the hierarchical structure, without re-implementing some form of binary search myself?
Add all the nodes to dictionary with the code as key. (you can do it once), the look-up in dictionary is basically O(1).
If you know the root, usage will be:
If you don’t you can call the
FillDictionary()method on all your nodes with the same dictionary.