【问题标题】:What is the best datastructure for hierarchical data representation in java?java中分层数据表示的最佳数据结构是什么?
【发布时间】:2019-10-07 10:49:21
【问题描述】:

我需要在 java 中创建一个可以表示数据层次结构的数据结构。示例用例如下图所示。

an organization hierarchy

在我的例子中,只有叶子级别会有数据,内部节点应该像索引一样。我应该能够使用多个键(复合键)从数据结构中获取数据。

是否可以使用嵌套映射,或者我应该为此用例实现 m 路树(B 树/B+ 树)。

【问题讨论】:

标签: java dictionary data-structures tree


【解决方案1】:

您可以为此用例实现 Trie。遍历复合键并返回数据(如果找到)。

类定义:

public class TrieNode {
    private HashMap<String, TrieNode> children;
    private Data data;
    private boolean isLeaf;

   // ...
}

查找查询将如下所示:

public Data find(List<String> compositeKey) {
    TrieNode current = root;
    for (String key: compositeKey) {
        TrieNode node = current.getChildren().get(key);
        if (node == null) {
            return null;
        }
        current = node;
    }
    if(current.isLeaf()) {
       return current.getData();
    } else {
       return null;
    }         
}

插入看起来像:

public void insert(List<String> compositeKey, Data data) {
    TrieNode current = root;

    for (String key: compositeKey) {
        current = current.getChildren()
          .computeIfAbsent(key, c -> new TrieNode());
    }
    current.setLeaf(true);
    current.setData(data);
}

【讨论】:

    【解决方案2】:

    如果嵌套数据的结构是常量,您可以使用带有属性的普通类。

    如果结构是动态的,我将使用Maps 接口并忽略实现。

    关于使用自定义树结构,如果可以使用类,那就更好了。如果您使用Maps,我会从HashMap 开始,如果您发现它有问题,您可以稍后将Map 替换为其他内容。

    【讨论】:

      【解决方案3】:

      显然你必须使用类似树的数据结构。这是它的示例代码。

      高级代码思路

      class Entity{  
          // declare you attributes and below two properties
      
          List<Entity> children;
      
          boolean isleafNode;// for parent node its 'false' and for leaf node it will 'true'
      
          }
      

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 1970-01-01
        • 2014-06-26
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2017-05-08
        相关资源
        最近更新 更多