[英]How to find overlapping / redundant nodes in a tree
我有一個大層次結構中的節點列表。 如何有效地確定我的哪些節點是列表中其他節點的后代?
具體來說,這是ASP.NET控件的列表。 我的代碼檢查了每個節點及其后代,因此我嘗試消除冗余。
一個簡單的例子是這棵樹:
Parent
/ \
Gladis Arthur
/ \
Jon Sam
我的列表包含{ Parent, Jon }
。
我想基於Parent
節點包含Jon
作為后代的事實,編寫一種將列表Parent
為“ Parent
的算法。
這是代碼:
public class Node
{
public Node(string name_, params Node[] children_)
{
this.children = children_;
}
public string name;
public Node[] children;
}
public class NodeAnalysis
{
public Node node;
public Node containingAncestor = null;
}
static void Main(string[] args)
{
Node jon = new Node("jon");
Node parent = new Node("parent",
new Node("Gladis",
jon,
new Node("Sam")),
new Node("Arthur")
);
List<NodeAnalysis> results = new List<NodeAnalysis>();
results.Add(new NodeAnalysis{ node = parent });
results.Add(new NodeAnalysis{ node = jon });
foreach (NodeAnalysis item in results)
{
// ??? populate item.containingAncestor
}
}
我想不出一種有效的算法來完成此任務。 我無法控制將節點添加到列表的順序。 似乎可以通過檢查樹和遍歷列表時已經確定的關系來對其進行優化。
**編輯: .parent
在Node
結構中可用。 使用.parent
可以發現祖先關系。
這是一種方法:
public static void RemoveDescendants(IList<Node> list)
{
for (int index = 0; index < list.Count; index++)
RemoveDescendants(list[index], list);
}
private static void RemoveDescendants(Node node, IList<Node> list)
{
foreach (var child in node.children)
{
list.Remove(child);
RemoveDescendants(child, list);
}
}
我發現這篇文章可能對您有用: http : //www.eng.auburn.edu/files/acad_depts/csse/csse_technical_reports/CSSE01-09.pdf
而且您可能還想查看這篇文章: http : //www.dmtcs.org/volumes/abstracts/pdfpapers/dm010116.pdf
我相信第一個直接回答您的問題。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.