English 中文(简体)
在C#中确定 no的深度
原标题:Find the depth of a node in C#

我有一份未经编辑的物体清单。 这些物体是一 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 = / }
}

Bin树:

      4
    /  
   2    5
  / 
 1  3

我需要一种算法,能够发现其中任何一点的深度。 我知道的唯一算法是中分辨率。 这意味着,我必须将物体清单转化为树。 认为...... 该网络没有明确的树木数据结构,你如何处理这个问题? 我是否必须把数据结构转换成树(我并不真的想写所有代码)。 是否有其他go子?

最佳回答
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;
    }

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签