import time
def build_tree_c(data):
"""建树:找儿子算法
1万层节点耗时(秒):7.0288989543914795
"""
for index, i in enumerate(data):
for j in data:
if i["id"]==j["parentId"]:
if "children" not in data[index].keys():
data[index]["children"] = []
data[index]["children"].append(j)
res = [i for i in data if i["parentId"]==0]
return res
def build_tree_p(data):
"""建树:找爸爸算法
1万层节点耗时(秒):0.005019187927246094
"""
# 建立一个 id 对 index 的字典
res = []
c_dict ={}
for index, i in enumerate(data):
c_dict[i["id"]] = index
# 用本节点的 parentId 通过字典找到父节点的index
for i in data:
if i['parentId'] == 0:
res.append(i)
else:
papa = data[c_dict[i["parentId"]]]
if "children" not in papa.keys():
papa["children"] = []
papa["children"].append(i)
# res = [i for i in data if i["parentId"]==0]
return res
# 创建一个1万个节点: [{'id': 0, 'parentId': 1}, {'id': 1, 'parentId': 2}, {'id': 2, 'parentId': 3}, ...{'id': 9999, 'parentId': 10000}]
data = [{"id": i+1,"parentId": i} for i in range(10000)]
# 将这1万个节点建树:
t1 = time.time()
res = build_tree_p(data)
# res = build_tree_c(data)
t2 = time.time()
st = t2-t1
print("Start time:\t%s\nStop time:\t%s\nElapsed time:\t%s" % (t1, t2, st))