具體我要代表如下:如何在Java中
- 在任何節點的樹能有孩子任意數量的
- (後根)每個父節點只是一個字符串(其子也是字符串)
- 我需要能夠獲得父和列出所有的孩子(某種列表或字符串數組)給定輸入字符串代表給定節點
- 動態填充基於參數關係的樹結構恩和孩子。 給出的例子是我有一個member1贊助另一個member2和member2贊助成員3等等。已經有表格記錄關係
有沒有可用的結構?
我的數據是從數據庫或表,我會遍歷的名稱和關係有關的信息,以確定該節點是根,父母或孩子。
因此,在循環過程中,我找到了一個孩子,我需要一個父對象的引用,以便在將子對象添加到其父對象之前,可以將其與父對象進行比較。
我找到的最接近的代碼。
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;
}
不知道你的問題是什麼。你在尋找代碼審查嗎? – bradimus
@bradimus沒有代碼審查,但尋找解決我的問題。動態數據正在被覆蓋 – newbieprogrammer