在这段生成代码处理外部分类树之前,对它进行审查。
构建保持插入顺序的 ID 到路径索引,拒绝环或重复 ID,并同时限制最大深度与最大节点数。
Python
def index_categories(root, max_depth=100):
index = {}
visited = set()
path = []
def visit(node, depth=0):
if depth > max_depth:
raise ValueError("category tree is too deep")
if node["id"] in visited:
return
path.append(node["name"])
index[node["id"]] = "/".join(path)
for child in node.get("children", []):
visit(child, depth + 1)
path.pop()
visited.add(node["id"])
visit(root)
return index
生成代码仅作示例,不代表任何特定模型