[英]How to create dynamic tree data structure in Java
具體來說,我需要代表以下內容:
有沒有可用的結構呢?
我的數據來自數據庫或列表,我將遍歷具有名稱和關系的信息,以確定該節點是根節點,父節點還是子節點。
因此,在循環中,我找到了一個孩子,我需要引用父對象,以便在將孩子添加到其父對象之前可以將其與父對象的關系進行比較。
我找到的最接近的代碼。
public class TreeNode<T> implements Iterable<TreeNode<T>> {
T data;
TreeNode<T> parent;
List<TreeNode<T>> children;
public TreeNode(T data) {
this.data = data;
this.children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> addChild(T child) {
TreeNode<T> childNode = new TreeNode<T>(child);
childNode.parent = this;
this.children.add(childNode);
return childNode;
}
// other features ...
}
Sample usage:
TreeNode<String> root = new TreeNode<String>("root");
{
TreeNode<String> node0 = root.addChild("node0");
TreeNode<String> node1 = root.addChild("node1");
TreeNode<String> node2 = root.addChild("node2");
{
TreeNode<String> node20 = node2.addChild(null);
TreeNode<String> node21 = node2.addChild("node21");
{
TreeNode<String> node210 = node20.addChild("node210");
}
}
}
到目前為止,這是我所做的。 父項將被最新條目覆蓋,因此我無法檢索之前添加的內容。
public static TreeNode<String> getSet1() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] items = line.split(":");
String name = items[0];
String parent = items[1];
String type = items[2];
if (parent.equalsIgnoreCase("-") && type.equalsIgnoreCase("mainparent")) {
root = new TreeNode<String>(name);
} else if (type.equalsIgnoreCase("ChildParent") && parent.equalsIgnoreCase(root.toString())) {
childParent = root.addChild(name);
} else if (type.equalsIgnoreCase("Child") && parent.equalsIgnoreCase(childParent.toString())) {
child = childParent.addChild(name);
}
}
return root;
}
您的圖表示一棵任意深度的樹,但是您的代碼僅處理祖父母->父->子關系(在根中有一個祖父母)。
我會忽略類型,因為您所需要的只是一個人的名字和他們父母的名字。 如果父名稱是破折號,則說明您擁有根。
現在,對於每個人,您都需要在樹中已有父節點(假設父節點在列表中的子節點之前-如果不是這樣,問題將變得更加復雜,因為您將不得不暫時存儲孤兒,每個新人都看他們是否是孤兒的父母)。
為了按名稱獲取父級,您應該將已經處理過的每個人存儲在與樹平行的第二個數據結構中。 第二個數據結構應使按名稱查找某人變得容易。 地圖,尤其是哈希表非常適合此操作。 它是這樣工作的:
Map processedPersonsMap=new Hashtable<String, TreeNode<String>>();
對於每個人,您都將它們存儲在地圖中,並按其名稱索引:
TreeNode<String> person=...;
processedPersonsMap.put(person.getData(), person);
當您讀一個新的人並且他們父母的名字不是破折號時,您會查找父母:
String parentName=items[1];
TreeNode<String> parent=processedPersonsMap.get(parentName);
這樣,無論樹有多深,您總會找到合適的父母。 但是,請記住,這需要一個有效的輸入文件,每個孩子都位於其父母之后,並且不包含循環引用或缺少父母。
如果不滿足這些條件,則必須明確處理它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.