,可以通过以下步骤实现:
以下是一个示例代码,用于实现上述步骤:
class Category:
def __init__(self, id, parent_id):
self.id = id
self.parent_id = parent_id
def get_longest_subcategory_chain(categories):
category_map = {}
for category in categories:
category_map[category.id] = category
longest_chain_length = 0
longest_chain_start = None
longest_chain_end = None
def dfs(category_id, chain_length, chain_start):
nonlocal longest_chain_length, longest_chain_start, longest_chain_end
if chain_length > longest_chain_length:
longest_chain_length = chain_length
longest_chain_start = chain_start
longest_chain_end = category_id
if category_id in category_map:
parent_id = category_map[category_id].parent_id
if parent_id != -1:
dfs(parent_id, chain_length + 1, chain_start)
for category in categories:
if category.parent_id == -1:
dfs(category.id, 1, category.id)
longest_chain = []
current_category_id = longest_chain_end
while current_category_id != longest_chain_start:
longest_chain.insert(0, current_category_id)
current_category_id = category_map[current_category_id].parent_id
longest_chain.insert(0, longest_chain_start)
return longest_chain
# 示例用法
categories = [
Category(1, -1),
Category(2, 1),
Category(3, 2),
Category(4, 3),
Category(5, 4),
Category(6, 5),
Category(7, 6),
Category(8, 7),
Category(9, 8),
Category(10, 9)
]
longest_chain = get_longest_subcategory_chain(categories)
print(longest_chain)
以上代码将输出最长子类别链 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
。
在实际应用中,可以根据具体的需求对代码进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云