我正在为某些类别和子类别搜索实现/数据结构。我正在考虑使用搜索树,但不确定如何开始实施。
让我告诉您数据的样子。它从后端以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": ""
},
]
},
]
因此,如果我必须将其绘制出来,它将看起来像这样:
因此,我希望能够找到任何东西。因此,例如,如果我要搜索项链,那么我也希望获得一条项链以获取以下路径:类别/配件/珠宝/项链
Is there a built in data structure for this ? i am coding in java. I suppose i also need the nodes sorted in some kind of order maybe A-Z.
so far i have this:
class Node{
String label;
List<Node> children;
}
but then how to search ? and is there a better data structure ? I do not want to iterate over all the nodes during a search, is there a way to sort the tree so i dont have to do that ? How i have it now i'd have to iterate over all the children. is there a way to maybe sort alphaetically perhaps or some kind of sort that would make the lookup faster ?
You need two things for this:
In your Node object, have a reference to the parent node as well:
class Node{
String label;
List<Node> children;
Node parent;
}
Create a HashMap that maps labels to the nodes:
HashMap<String, Node> labelsToNodes;
然后使用HashMap中的get()方法完成搜索。您可以通过重复获取父节点来获得类别列表。让我知道您是否想要此代码,然后我将其添加(我现在时间很紧)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句