2010-11-22 86 views
0

我有一棵樹,所有葉子都有索引,當樹從數據庫中遞歸堆積時,數據庫會通過索引來排序樹。首先,它獲得按索引排序的根節點等等。現在我需要實現操作,用戶可以通過按向上/向下箭頭圖標來排序這些索引。當用戶按下時,索引應該採用在它自己的索引下的索引,並且當向上箭頭被按下時,它應該反過來。我只是不知道什麼是實現這種功能的最佳方式。遞歸樹索引的順序?

+0

是否所有節點都有索引或僅留下?如何生成索引? – 2010-11-22 07:48:48

+0

所有節點都有索引,所有節點都在同一個數據庫表中。索引創建爲所有索引的最高索引,如同deafult。 – newbie 2010-11-22 07:58:02

回答

1

由於你的問題有點含糊,這個答案假定你知道你在做什麼,當涉及到數據庫的東西(如果不是,我會推薦hibernate for java),下面的代碼是爲了給你一些想法實施您的解決方案

//If I have understood your question, you want two nodes to swap position in the tree structure 
public static swapNode(Node parent, Node child) 
{ 
    Long superId = parent.getParentId(); 
    child.parentId(superId); 
    parent.setParentId(child.getId()); 
    child.setId(parentId); 
    //update children lists of parent and child 
    //update parent ids of children lists 

    //save changes to database 
} 

//create tree structure from database. Assumes nodes have been loaded from a database 
//table where each row represents a node with a parent id column the root node which has parent id null) 
//invoke this with all nodes and null for parentId argument 
public static List<Node> createNodeTree(List<Node> allNodes, Long parentId) 
{ 
    List<Node> treeList = new ArrayList<Node>(); 
    for(Node node : nodes) 
    { 
     if(parentIdMatches(node, parentId)) 
     { 
      node.setChildren(createNodeTree(allNodes, node.getId())); 
      treeList.add(node); 
     } 
    } 
    return treeList; 
} 

private static boolean parentIdMatches(Node node, Long parentId) 
{ 
    return (parentId != null && parentId.equals(node.getParentId())) 
     || (parentId == null && node.getParentId() == null); 
} 

//The objects loaded from the database should implement this interface 
public interface Node 
{ 
    void setParentId(Long id); 
    Long getParentId(); 
    Long getId(); 
    List<Node> getChildren(); 
    void setChildren(List<Node> nodes); 
}