2011-03-16 118 views
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); 
    } 
} 

回答

1

這不是一個二叉樹或一個非常複雜的樹,這樣你不需要一個「動態的解決方案」和我猜你不是指動態編程?無論如何,你想要的是深度優先搜索樹插入一個新的節點,因爲這不是一個非常複雜的樹,你必須分割一個節點。

+0

感謝您的快速回復。那麼即使樹列表中有很多對象,我也可以使用deph-first搜索來填充樹狀結構?我的意思是填充樹的代碼現在不是動態的,因爲我在我的應用程序中爲每個parentid an使用了一個if結構,這裏有很多parentids。 – NielsVE 2011-03-16 13:00:28

+0

這是一個很好的關於遞歸和深度優先搜索的教程,但它是用php我最喜歡的語言:http://devzone.zend.com/article/1235 – Bytemain 2011-03-16 15:38:17