0
기본적으로 내가 할 일은 정렬되지 않은 목록의 개체를 트리 구조로 구성하는 것입니다. 이 트리는 목록에있는 객체의 parentId 속성을 기반으로 채워야합니다. 따라서 목록의 객체가 parentid=0
이면 루트입니다. parentid=1
인 경우 id =1
인 개체의 자식입니다. '나무를 채우는 것'아래에 문제가 있습니다. 이제 정적으로 채워지지만 나무를 채우기 위해서는 역동적 인 방법이 필요합니다. 누군가가 나에게 조언을 해줄 수 있기를 바랍니다. 나는 내 문제를 추상화하고 다음 코드를 만들었 :나무 바닥을 채우기
public class Node {
private int id,parentid;
private String text;
public int getParentid() {
return parentid;
}
public void setParentid(int parentid) {
this.parentid = parentid;
}
Node(int id , String s,int pid){
setId(id);
setParentid(pid);
setText(s);
}
public int getNummer() {
return id;
}
public void setId(int nummer) {
this.id = nummer;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
public class NodeTreeSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Tree");
//The unsorted list with the objects
Collection<Node> treeList = new ArrayList<Node>();
treeList.add(new Node(1,"Rootnode",0));
treeList.add(new Node(2,"Child of node with id 1",1));
treeList.add(new Node(3, "Child of node with id 1", 1));
treeList.add(new Node(4, "Child of node with id 2", 2));
treeList.add(new Node(5, "Child of node with id 2", 2));
DefaultMutableTreeNode root=new DefaultMutableTreeNode("Root");
//Filling the tree
for(Node n:treeList){
if(n.getParentid()==0){
root = new DefaultMutableTreeNode(n.getText());
}
if(n.getParentid()==1){
root.add(new DefaultMutableTreeNode(n.getText()));
}
if(n.getParentid()==2){
}
}
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
빠른 답장을 보내 주셔서 감사합니다. 그래서 트리 엘 리스스트에 많은 객체가 있더라도 디프 퍼스트 검색을 사용하여 트리를 채울 수 있습니까? 나는 트리를 채우는 코드가 동적이지 않다는 것을 의미했다. 왜냐하면 나는 각 parentid에 if 구조를 사용하고 있기 때문에 내 애플리케이션에는 많은 parentid가있다. – NielsVE
다음은 재귀 및 깊이 우선 검색에 대한 유용한 자습서입니다.하지만 필자가 가장 좋아하는 언어 인 http://devzone.zend.com/article/1235 – Bytemain