簡體   English   中英

如何在層次結構中查找根元素

[英]How to find the root element in a hierarchical structure

我有這種情況設置:

具有屬性“Children”的對象,它是相同類型的List。 結構的深度是未知的。 這就是對象的樣子:

public class CustomType
{
   public Guid ID { get; set; }
   public string Name { get; set; }
   public List<CustomType> Children { get; set; }
}

現在我想搜索一個特定的名稱,如果我找到了一個與此名稱匹配的元素,我想知道它的根元素。 例如:

  • rootElement的
    • 為anyelement
      • 為anyelement
        • FoundElement

我已經有了FoundElement,但我想知道它是頂級的父元素。 我希望我的問題是可以理解的。 主要問題是對象中不存在的父鏈接...

這么長的克里斯

正如你所說,理想的是在類上有一個Parent屬性。 但是,如果要求不這樣做,那么您的方法應該是檢查所有候選根節點的所有后代。 這可以遞歸地完成,如:

private bool HasDescendent(CustomType parent, CustomType descendent)
{
    if(parent.Children.Contains(descendent))
        return true;
    return parent.Children.Any(child => HasDescendent(child, descendent);
}

private CustomType FindRoot(IEnumerable<CustomType> candidateRoots, CustomType node)
{
    return candidateRoots.First(root => HasDescendent(root, node));
}

實現這一目標的唯一方法是遞歸(我暫時沒有做過C#,所以這里有一些偽代碼):

list<items> findPath(root, needle):
    if root == needle:
         return [needle]
    for child in root.children:
         if findPath(child, needle) != Null:
              return [root].concat(findPath(child, needle))
    return Null

這應該是從根節點到針的路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM