Personally I'd probably map the data representation to something closer to what you are actually representing.
Dictionary<string, List<string>> Tree;
public void BuildTree(string[,] a)
{
if (a == null)
throw new ArgumentNullException("a");
Tree = new Dictionary<string, List<string>>();
int rows = a.GetLength(0);
for (int r = 0; r < rows; r++)
{
string key = a[r, 0];
List<string> subTree;
if (!Tree.TryGetValue(key, out subTree))
{
subTree = new List<string>();
Tree.Add(key, subTree);
}
subTree.Add(a[r, 1]);
}
}
public IEnumerable<string> TraverseTree(string startNode)
{
if (startNode == null)
throw new ArgumentNullException("startNode");
yield return startNode;
List<string> subTree;
if (Tree.TryGetValue(startNode, out subTree))
{
foreach (var node in subTree.SelectMany(n => TraverseTree(n)))
{
yield return node;
}
}
}
TraverseTree("b")
will return "b" and all of the
nodes under it:
string[,] str = {{"a","b"},
{"a","c"},
{"b","b1"},
{"b","b2"},
{"b","b3"},
{"b3","b31"},
{"b3","b32"},
{"b31","b311"},
{"b32","b321"}};
BuildTree(str);
TraverseTree("b");
"b", "b1", "b2", "b3", "b31", "b311", "b32", "b321"