我正在为我拥有的某些类别和子类别搜索实现/数据结构。我正在考虑使用搜索树,但不确定如何开始实现。
让我向您展示数据的样子。它实际上是从后端作为 json 结构来到我这里的,但它看起来像这样:
[
{
"id": 94,
"category_name": "New In", //this is the category category_name
"description": "",
"children": [ //this is the category children which can also be a sub-category
{
"id": 322,
"category_name": "New Studio",
"description": "Chic, sophisticated and polished with a classic edge."
},
{
"id": 365,
"category_name": "New Soho",
"description": "Fresh, eclectic, and trendy. Oozes effortless cool."
},
{
"id": 809,
"category_name": "Summer Collection",
"description": "Your ultimate summer look"
}
]
},
{
"id": 12,
"category_name": "Clothes",
"description": "",
"children": [
{
"id": 22,
"category_name": "All Clothes",
"description": ""
},
{
"id": 63,
"category_name": "Tops",
"description": "",
"children": [
{
"id": 5,
"category_name": "All Tops",
"description": ""
}
]
},
{
"id": 641,
"category_name": "Accessories",
"description": "",
"children": [
{
"id": 61,
"category_name": "All Accessories",
"description": ""
},
{
"id": 622,
"category_name": "Jewelry",
"description": "",
"children": [ // here is an example of a child that is a sub-category also
{
"id": 52,
"category_name": "All Jewelry",
"description": ""
},
{
"id": 68,
"name": "Necklaces",
"description": ""
},
{
"id": 69,
"name": "Bracelets",
"description": ""
},
]
},
]
所以如果我不得不把它画出来,它看起来像这样:
所以我希望能够找到任何东西的路径。因此,例如,如果我想搜索项链,那么我想要一条项链来获得路径:Categories/Accessories/Jewelry/Necklaces
是否有内置的数据结构?我在用java编码。我想我还需要按某种顺序排序的节点,可能是 A-Z。
到目前为止我有这个:
class Node{
String label;
List<Node> children;
}
但是如何搜索呢?有没有更好的数据结构?我不想在搜索期间遍历所有节点,有没有一种方法可以对树进行排序,这样我就不必这样做了?我现在如何拥有它我必须遍历所有 child 。有没有一种方法可以按字母顺序排序或某种可以加快查找速度的排序?
最佳答案
为此你需要两件事:
在您的 Node 对象中,也有对父节点的引用:
class Node{
String label;
List<Node> children;
Node parent;
}
创建一个将标签映射到节点的 HashMap:
HashMap<String, Node> labelsToNodes;
然后使用 HashMap 中的 get() 方法进行搜索。您可以通过重复获取父节点来获取类别列表。如果您需要此代码,请告诉我,我会添加它(我现在时间不多)。
关于Java - 具有多个节点的树数据结构 - 如何有效地搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994171/