我正在寻找一种实现/数据结构来管理我的某些类别和子类别。我考虑使用搜索树,但不确定如何开始实现。
让我展示一下数据的样子。实际上,它作为一个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": ""
},
]
},
]
如果我需要画出这个结构,它看起来会像这样:
所以我想要能够获取任何东西的路径。例如,如果我想搜索项链,那么除了得到一条项链之外,我还希望得到路径:类别/配件/珠宝/项链
是否有内置的数据结构可以实现这一点?我正在使用Java进行编码。我想也许还需要对节点按某种顺序排序,比如按字母顺序A-Z。
到目前为止,我有以下代码:
class Node{
String label;
List<Node> children;
}
但是如何进行搜索?是否有更好的数据结构?我不想在搜索过程中迭代所有的节点,有没有一种方法可以对树进行排序,使我不必这样做?按照我的现有方式,我必须迭代所有的子节点。也许有一种按字母顺序或某种排序方式可以使查找更快吗?
List<Node>
。 - Alex