2011-06-22 3 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:申し訳ありませんが、(Key、Children) – 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); 

は、あなたは少し異なるツリーを(リンク内の情報を参照してください)

関連する問題