Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中查找节点的深度#_C#_Algorithm_Binary Tree - Fatal编程技术网

C# 在C中查找节点的深度#

C# 在C中查找节点的深度#,c#,algorithm,binary-tree,C#,Algorithm,Binary Tree,我有一个未排序对象的列表。这些对象表示一个二叉树 对象列表: 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

我有一个未排序对象的列表。这些对象表示一个二叉树

对象列表:

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 = / }
}
我需要一个算法,可以找到这些节点的深度。我知道的唯一算法是深度优先搜索。这意味着我必须将对象列表转换为树。考虑到.NET没有明确的树数据结构,您将如何解决这个问题?我是否必须将数据结构转换成一棵树(我真的不想写所有的代码)。还有别的算法吗

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);

简单但效率低。

您可以将对象添加到字典中,使用左右两侧的每个值作为键,Id作为值(基本上是反向映射)。然后像这样编写递归函数

Dictionary<int, int> map;
    int depth(int node)
    {
        if (!map.ContainsKey(node))
            return 0;
        return depth(map[node]) + 1;
    }
字典地图;
整数深度(整数节点)
{
如果(!map.ContainsKey(节点))
返回0;
返回深度(映射[节点])+1;
}

你可以做一本
字典。将节点ID存储为键,将节点的父节点存储为值。请注意,这意味着在字典中为原始列表中的每个对象存储零条、一条或两条记录。然后,要查找节点的深度,只需计算在用完之前可以获得父节点的次数。大概是这样的:

public static int NodeDepth(int node, Dictionary<int,int> parents)
{
     int depth = 0;
     while (parents.ContainsKey(node))
     {
          node = parents[node];
          depth++;
     }
     return depth;
}
public static int nodededepth(int节点、字典父节点)
{
int深度=0;
while(parents.ContainsKey(节点))
{
节点=父节点[节点];
深度++;
}
返回深度;
}
public static int NodeDepth(int node, Dictionary<int,int> parents)
{
     int depth = 0;
     while (parents.ContainsKey(node))
     {
          node = parents[node];
          depth++;
     }
     return depth;
}