为了账号安全,请及时绑定邮箱和手机立即绑定

java中分层数据表示的最佳数据结构是什么?

java中分层数据表示的最佳数据结构是什么?

一只甜甜圈 2023-09-27 17:15:16
我需要在java中创建一个可以表示数据层次结构的数据结构。示例用例如下图所示。组织层次结构在我的例子中,只有叶子级别才会有数据,内部节点应该像索引一样工作。我应该能够使用多个键(复合键)从数据结构中获取数据。是否可以使用嵌套映射,或者我应该为此用例实现一个 m 路树(B 树/B+ 树)。
查看完整描述

3 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

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


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


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


查看完整回答
反对 回复 2023-09-27
?
ibeautiful

TA贡献1993条经验 获得超5个赞

您可以为此用例实现 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);

}


查看完整回答
反对 回复 2023-09-27
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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


高级代码思想


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'


    }


查看完整回答
反对 回复 2023-09-27
  • 3 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信