Algorithm bug traversal_to_tree
downdawn opened this issue · 4 comments
downdawn commented
The traversal_to_tree algorithm has a bug, which has a lot to do with the order. If the parent is behind the child, the data will be empty.
wu-clan commented
Can you provide some fake data? Or an MRE?
downdawn commented
async def get_tree_data(
...
# nodes = await get_tree_nodes(row)
nodes = row
match build_type:
...
data = [
{'id': 1, 'parent_id': 2, 'name': '总公司', 'leader': '张三', 'phone': '13888888888', 'status': 1, 'sort': 1},
{'id': 2, 'parent_id': None, 'name': '财务部', 'leader': '李四', 'phone': '13888888888', 'status': 1, 'sort': 1},
{'id': 3, 'parent_id': 2, 'name': '人事部', 'leader': '王五', 'phone': '13888888888', 'status': 1, 'sort': 2},
]
if __name__ == '__main__':
tree_data = asyncio.run(get_tree_data(data, build_type=BuildTreeType.traversal))
print(tree_data)
result
[
{
"id": 2,
"parent_id": null,
"name": "财务部",
"leader": "李四",
"phone": "13888888888",
"status": 1,
"sort": 1,
"children": [
{
"id": 3,
"parent_id": 2,
"name": "人事部",
"leader": "王五",
"phone": "13888888888",
"status": 1,
"sort": 2
}
]
}
]
wu-clan commented
Hi, @downdawn
I tested the data, but there was no problem.
This is a complete MRE:
import asyncio
from pprint import pp
from backend.app.utils.build_tree import traversal_to_tree, recursive_to_tree
data = [
{'id': 1, 'parent_id': 2, 'name': '总公司', 'leader': '张三', 'phone': '13888888888', 'status': 1, 'sort': 1},
{'id': 2, 'parent_id': None, 'name': '财务部', 'leader': '李四', 'phone': '13888888888', 'status': 1, 'sort': 1},
{'id': 3, 'parent_id': 2, 'name': '人事部', 'leader': '王五', 'phone': '13888888888', 'status': 1, 'sort': 2},
]
if __name__ == '__main__':
data.sort(key=lambda x: x['sort'])
tree_data1 = asyncio.run(traversal_to_tree(data))
pp(tree_data1)
tree_data2 = asyncio.run(recursive_to_tree(data))
pp(tree_data2)
assert tree_data1 == tree_data2
assert len(tree_data1[0]['children']) == 2
assert len(tree_data2[0]['children']) == 2
downdawn commented
my problem, no update