我需要在Java中创建一个可以表示数据层次结构的数据结构。下图显示了示例用例。
an organization hierarchy
在我的情况下,仅叶子级别具有数据,内部节点应像索引一样工作。我应该能够使用多个键(复合键)从数据结构中获取数据。
使用嵌套映射可以吗,或者在这种情况下我应该实现m路树(B树/ B +树)。
最佳答案
您可以为此用例实现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);
}
关于java - Java中分层数据表示的最佳数据结构是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58268056/