2011-06-22 57 views
0

我有一個列表顯示出如下面的樹數據結構:如何從字典中顯示的樹中獲取每個節點的級別?

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 

我不知道你能不能幫我與創建項目和水平的詞典:

Dictioanry<ItemID, Level>

+4

列表只支持一個通用的參數(和你有2個)。你能發佈一些真正的C#嗎?我不明白你的僞代碼。 –

+0

@ agent-j:對不起,這是一個(密鑰,兒童) – Jose

+1

的字典,這更好。現在,你的意思是水平=深度?那麼你想要這樣的字典嗎? {{1,1},{2,2},{3,3},{4,4},{5,4},}? 3有2個孩子(4和5)。 4還有一個5的孩子?那麼5會有什麼水平? 4 /和/ 5? –

回答

0

不知道這是最好的解決方案,但應該工作:

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

如果您使用此node class,你可以簡單地這樣做:

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

您需要填寫樹有點不同(見鏈接的信息)

相關問題