Find the depth of a node in C#
I have a list of unsorted objects. Those objects represent a binary tree.
List of objects:
new List<Object>
{
new { Id = 3, Left = /, Right = / }
new { Id = 5, Left = /, Right = / }
new { Id = 4, Left = 2, Right = 5 }
new { Id = 2, Left = 1, Right = 3 }
new { Id = 1, Left = /, Right = / }
}
Binary Tree:
4
/ \
2 5
/ \
1 3
I need an algorithm which will find the depth of 开发者_开发技巧any of these nodes. The only algorithm I am aware of is Depth-first search. It implies that I have to convert the list of objects into a tree. Considering that .NET has no explicit tree data structure how would you approach this problem? Do I have to convert the data structure into a tree (I don't really want to write all the code). Is there other algo?
int nodeToFind = 2;
var currentNode = list.Single(n => n.Id == nodeToFind);
int depth = 0;
while ((currentNode = list
.FirstOrDefault(i => i.Left == currentNode.Id || i.Right == currentNode.Id)) != null)
depth++;
Console.WriteLine(depth);
Simple, but inefficient.
you could just add your objects to a dictionary, using each of the left and right values as keys and the Id as the value (basically a reverse map). then you write your recursive function like this...
Dictionary<int, int> map;
int depth(int node)
{
if (!map.ContainsKey(node))
return 0;
return depth(map[node]) + 1;
}
You could just make a Dictionary<int,int> parents
. Store the node ID as the key, and the node's parent as the value. Note, that this means storing zero, one, or two records in the dictionary for each object in the original list. Then to find the depth of a node, just count the number of times you can get a parent node before you run out. Something like this:
public static int NodeDepth(int node, Dictionary<int,int> parents)
{
int depth = 0;
while (parents.ContainsKey(node))
{
node = parents[node];
depth++;
}
return depth;
}
精彩评论