代码之家  ›  专栏  ›  技术社区  ›  newbie

递归树索引的顺序?

  •  0
  • newbie  · 技术社区  · 15 年前

    我有一棵树,所有的叶子都有索引,当树从数据库中被重新分层时,数据库将按索引对树进行排序。首先,它获取按索引等排序的根节点。现在我需要实现用户如何通过按上/下箭头图标对这些索引排序的操作。当用户按下时,索引应该取它自己索引下的索引,当按下向上箭头时,索引应该取它自己索引下的索引,反之亦然。我只是不知道什么是实现这种功能的最佳方式。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Matt    15 年前

    由于您的问题有点含糊,这个答案假设您知道在数据库方面您在做什么(如果不是的话,我建议您使用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);
    }