每个级别具有多个子级(已排序)的 Java 树结构

标签 java data-structures

我正在处理一个扁平的对象列表,但它们在父子关系中相互关联。一个对象可以有任意数量的 child ,或者根本没有。我需要将这些对象显示为一棵树,显示这些关系。树的每一层都应该排序(对象Collections.sort() 兼容)。

问题分为两部分:

  1. Java 是否有开箱即用的数据结构来保存这样一棵树,还是我需要从头开始编写一个? (这不是一项艰巨的任务,但是重新发明轮子是没有意义的)我知道 Swing 中的 DefaultTreeModel ......但是这个应用程序在服务器端运行,并且使用 Swing 包将得到在代码审查中不受欢迎。

  2. 将平面列表加载到此类数据结构中的最佳模式是什么?我的第一个想法是识别根级对象,然后使用递归方法向下遍历它们的子孙等。但是,对于树中每个级别的对等体排序的要求......我是不确定是在构建树时担心这个问题更有意义,还是稍后在解析树以供显示时担心它。

最佳答案

这是一个在所有级别上都使用 TreeSet 的快速简单的 Tree 实现(您可以提供一个比较器,或者将使用自然排序):

public class Tree<T> {

    private final Node<T> rootElement;

    public void visitNodes(final NodeVisitor<T> visitor){
        doVisit(rootElement, visitor);
    }

    private static <T> boolean doVisit(final Node<T> node,
        final NodeVisitor<T> visitor){
        boolean result = visitor.visit(node);
        if(result){
            for(final Node<T> subNode : node.children){
                if(!doVisit(subNode, visitor)){
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    public interface NodeVisitor<T> {

        boolean visit(Node<T> node);
    }

    public Node<T> getRootElement(){
        return rootElement;
    }

    private static final class NodeComparator<T> implements Comparator<Node<T>>{

        private final Comparator<T> wrapped;

        @Override
        public int compare(final Node<T> o1, final Node<T> o2){
            return wrapped.compare(o1.value, o2.value);
        }

        public NodeComparator(final Comparator<T> wrappedComparator){
            this.wrapped = wrappedComparator;
        }

    }

    public static class Node<T> {

        private final SortedSet<Node<T>> children;

        private final Node<T> parent;

        private T value;

        private final Comparator<?> comparator;

        @SuppressWarnings("unchecked")
        Node(final T value, final Node<T> parent, final Comparator<?> comparator){
            this.value = value;
            this.parent = parent;
            this.comparator = comparator;
            children =
                new TreeSet<Node<T>>(new NodeComparator<T>((Comparator<T>) comparator));
        }

        public List<Node<T>> getChildren(){
            return new ArrayList<Node<T>>(children);
        }

        public Node<T> getParent(){
            return parent;
        }

        public T getValue(){
            return value;
        }

        public void setValue(final T value){
            this.value = value;
        }

        public Node<T> addChild(final T value){
            final Node<T> node = new Node<T>(value, this, comparator);
            return children.add(node) ? node : null;
        }

    }

    @SuppressWarnings("rawtypes")
    private static final Comparator NATURAL_ORDER = new Comparator(){

        @SuppressWarnings("unchecked")
        @Override
        public int compare(final Object o1, final Object o2){
            return ((Comparable) o1).compareTo(o2);
        }
    };

    private final Comparator<?> comparator;

    public Tree(){
        this(null, null);
    }

    public Tree(final Comparator<? super T> comparator){
        this(comparator, null);
    }

    public Tree(final Comparator<? super T> comparator, final T rootValue){
        this.comparator = comparator == null ? NATURAL_ORDER : comparator;
        this.rootElement = new Node<T>(rootValue, null, this.comparator);
    }

    public Tree(final T rootValue){
        this(null, rootValue);
    }

}

下面是一些针对它的示例代码:

final Tree<Integer> tree = new Tree<Integer>();
final Node<Integer> rootNode = tree.getRootElement();
rootNode.setValue(1);
final Node<Integer> childNode = rootNode.addChild(2);
final Node<Integer> newChildNode = rootNode.addChild(3);
newChildNode.addChild(4);
tree.visitNodes(new NodeVisitor<Integer>(){

    @Override
    public boolean visit(final Node<Integer> node){
        final StringBuilder sb = new StringBuilder();
        Node<Integer> curr = node;
        do{
            if(sb.length() > 0){
                sb.insert(0, " > ");
            }
            sb.insert(0, String.valueOf(curr.getValue()));
            curr = curr.getParent();
        } while(curr != null);
        System.out.println(sb);
        return true;
    }
});

输出:

1
1 > 2
1 > 3
1 > 3 > 4

关于每个级别具有多个子级(已排序)的 Java 树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748684/

相关文章:

data-structures - 为什么redis SET中插入的时间复杂度是O(n)?

java - 每季度的天数?

java - "Removing"数组中的偶数并将奇数移动到前面

haskell - 纯功能性(持久性)环形缓冲区

algorithm - 使用动态规划的最低成本

java - 如何在 if 语句中使用 java empty HashSet?

java - 在 Java 代码中调用 @Canonical Groovy POGO 构造函数

java - Netbeans 中的 Jaxb 错误

java - Spring启动REST Controller : different custom validators for POST and PUT methods receiving the same object

algorithm - 唯一元素数组的最小间隔