C# 如何从字典中演示的树中获取每个节点的级别?

C# 如何从字典中演示的树中获取每个节点的级别?,c#,linq,dictionary,tree,C#,Linq,Dictionary,Tree,我有一个树状数据结构,如下所示: Dictionary<int, List<int>> // Key, list of children Data(1) = { 2 } // root Data(2) = { 3 } Data(3) = { 4, 5 } Data(4) = { 5 } Data(5) = { } // leaf 我想知道您是否可以帮助我创建一个项目和级别的字典: DictionAnry不确定这是否是最好的解决方案,但应该有效: v

我有一个树状数据结构,如下所示:

Dictionary<int, List<int>> // Key, list of children

Data(1) = { 2 } // root
Data(2) = { 3 }
Data(3) = { 4, 5 }
Data(4) = { 5 }
Data(5) = {   } // leaf
我想知道您是否可以帮助我创建一个项目和级别的字典:


DictionAnry不确定这是否是最好的解决方案,但应该有效:

        var data = new Dictionary<int, List<int>>();
        data[1] = new List<int> { 2 };
        data[2] = new List<int> { 3 };
        data[3] = new List<int> { 4, 5 };
        data[4] = null;
        data[5] = new List<int> { 6, 7 };
        data[6] = new List<int> { 8 };
        data[7] = null;
        data[8] = null;

        var allparents = new Dictionary<int, int>(data.Count);

        foreach (var node in data) {
            if (node.Value != null) {
                foreach (var child in node.Value) {
                    allparents[child] = node.Key;
                }
            }
        }

        int root = data.Keys.Except(allparents.Keys).First();
        int maxdepth = 1;
        foreach (int child in allparents.Keys) {
            int depth = 1;
            int parent = child;
            while (parent != root) {
                ++depth;
                parent = allparents[parent];
            }
            if (depth > maxdepth) {
                maxdepth = depth;
            }
        }
        Console.WriteLine(maxdepth);
如果使用此选项,您可以简单地执行以下操作:

nodes.All.ToDictionary(n => n.Value, n => n.Level);

您需要填充稍微不同的树,请参见链接列表中的信息仅支持一个通用参数,您有2个。你能发一些真正的c吗?我不明白你的伪代码。@j探员:对不起,这是一本钥匙字典,孩子。这样更好。你是说水平=深度吗?你想要一本这样的字典吗?{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 4}, }? 这三个人有两个孩子,一个是4岁,一个是5岁。4岁的孩子也有5岁?那么5级应该是什么级别呢?四分之一和五分之一?@j探员:你说得对,是的,深度。实际上是最大值。我认为字典和树没有最大值树中的每个节点/叶都有它的深度、父节点和子节点,除了根节点没有父节点