2016-11-28 93 views
4

我有一個問題,從字符串列表中創建樹。 這裏我輸入數據:從列表c創建樹#

IReadOnlyList<IReadOnlyList<string>> listeDesParcours = new List<IReadOnlyList<string>> 
    { 
     new List<string> 
     { 
      "Produit","Sinistre","Particulier","Auto","RC" 
     }, 
     new List<string> 
     { 
      "Produit","Sinistre","Entreprise","Auto","2roues" 
     }, 
     new List<string> 
     { 
      "Produit","reclamation","Particulier","Moto","PP" 
     }, 
     new List<string> 
     { 
      "Produit","reclamation","Entreprise","Auto","TT" 
     }, 
     new List<string> 
     { 
      "Produit","reclamation","Entreprise","Auto","PP" 
     }, 
     new List<string> 
     { 
      "Produit","souscription","Salarie","Aviation" 
     }, 
     new List<string> 
     { 
      "Produit","souscription","Salarie","Aviation","Airbus" 
     }, 
     new List<string> 
     { 
      "Produit","reclamation","Reclamation tout court" 
     }, 
     new List<string> 
     { 
      "Produit","Produit tout court" 
     }, 
     new List<string> 
     { 
      "Produit","Sinistre","Entreprise","Auto","5roues" 
     } 
    }; 

正如你所看到的,它是一個字符串列表和列表我想從它 得到了一棵樹。 這裏是我的目標,我想到底

public class Node 
     { 
      public string Value { get; set; } 
      public List<Node> Childs { get; set; } 
     } 

返回,這是我想要得到的結構

        RootElement 
             | 
     ___________________________Produit__________________________ 
    /       |        \ 
__sinistre___________   reclamation_______     Souscription 
|     \    /   \      |   
entreprise  particulier  entreprise particulier   Salarie______________ 
    |    |    |   |      |    \ 
    auto   auto    auto  auto     Marine    Aviation__ 
                          / \ 
                          Airbus Boing 

任何人都可以點我請一個遞歸的方法,讓我請從列表中填充樹?

在此先感謝

編輯: 最後發表評論我要澄清,我想,我創建了一個類型節點的對象後......但是我的輸入字符串是列表的列表

+0

嗨!如果能解決您的問題,您是否可以接受非遞歸方法? –

+0

@KarouiHaythem是的,如果我可以得到所描述的對象,這將是偉大的! :) – Ytem

+0

如果您想使用自己的結構或想要使用標準清單列表 –

回答

1
var root = new Node() { Value = "RootElement", Childs = new List<Node>() }; 
    foreach (var route in listeDesParcours) 
    { 
     var current = root; 
     foreach (var value in route) 
     { 
      var child = current.Childs.Find(x => x.Value == value); 
      if (child == null) 
      { 
       child = new Node() { Value = value, Childs = new List<Node>() }; 
       current.Childs.Add(child); 
      } 
      current = child; 
     } 
    } 

注意,有一個在listeDesParcours數據和繪製樹之間的一些差異,所以在root結果樹看起來並不完全相同你。

0
  1. 創建將返回的rootNode。

  2. 寫像 populateRootNode(Node rootNode, IReadOnlyList> input)

    的功能在此功能中,每個列表創建節點 ,附加裝箱節點根節點的孩子。併爲每個列表調用addChildrenNodes(請參閱3)。

  3. 撰寫功能,如 addChildrenNodes(Node ParentNode, List input)

    在此函數中,爲給定列表的每個項目創建節點,並將創建的節點添加爲當前節點的子節點。

  4. 返回的根節點

+0

這不是遞歸方法,因爲輸入不是統一節點的樹。 –