1.将如下nodes列表转化为树结构
nodes = [
{'id': 1, 'name': '1', 'parent_id': None},
{'id': 2, 'name': '2', 'parent_id': 1},
{'id': 3, 'name': '3', 'parent_id': 1},
{'id': 4, 'name': '4', 'parent_id': 2},
{'id': 5, 'name': '5', 'parent_id': 3},
{'id': 6, 'name': '6', 'parent_id': 5},
]
tree = [node for node in nodes if node['parent_id'] is None]
for node in nodes:
node['children'] = [n for n in nodes if node['id'] == n['parent_id']]
以上三行代码就搞定啦
有如下树结构:
tree = [{'id':1 ,'name': '1', 'children': [{'id':2 ,'name': '2'}, {'id':3 ,'name': '3', 'children': [{'id':4 ,'name': '4'},{'id':5 ,'name': '5'}]}]}]
给定某个子节点,如何获取所有父节点?
def get_parent_name(node_id, tree, nodes=[]):
"""获取树结构某个节点的所有父节点名称列表"""
for node in tree:
if node['id'] == node_id:
return nodes
else:
if 'children' in node:
result = get_parent_name(node_id, node['children'], nodes + [node['name']])
if not result:
continue
return result
return []
else:
return []
如果我想获取所有子节点列表?
def get_current_node(node_id, tree):
"""获取树结构某个节点"""
for node in tree:
if node['id'] == node_id:
return node
else:
if 'children' in node:
result = get_current_node(node_id, node['children'])
if not result:
continue
return result
def get_sub_node_ids(node, sub_node_ids=None):
"""获取树结构某个节点的所有子节点id"""
if sub_node_ids is None:
sub_node_ids = []
if 'children' in node:
for n in node['children']:
sub_node_ids.append(n['id'])
sub_node_ids = get_sub_node_ids(n, sub_node_ids)
return sub_node_ids
node = get_current_node('2', tree)
sub_node_ids = get_sub_node_ids(node)
2、补充算法
def get_current_node(node_id, tree):
"""深度优先算法:获取树结构某个节点"""
for node in tree:
if node['id'] == node_id:
return node
else:
if 'children' in node:
result = get_current_node(node_id, node['children'])
if not result:
continue
return result
def get_current_node_(node_id, tree):
"""广度优先算法:获取树结构某个节点"""
queue = [tree] if isinstance(tree, dict) else tree
while queue:
node = queue.pop(0)
if node['id'] == node_id:
return node
else:
if 'children' in node:
queue.extend(node['children'])
def get_sub_node_ids(node, sub_node_ids=None):
"""深度优先算法:获取树结构某个节点的所有子节点id"""
if sub_node_ids is None:
sub_node_ids = []
if 'children' in node:
for n in node['children']:
sub_node_ids.append(n['id'])
sub_node_ids = get_sub_node_ids(n, sub_node_ids)
return sub_node_ids
def get_sub_node_ids_(node, sub_node_ids=None):
"""广度优先算法:获取树结构某个节点的所有子节点id"""
if sub_node_ids is None:
sub_node_ids = []
queue = [node]
while queue:
node = queue.pop(0)
sub_node_ids.append(node['id'])
if 'children' in node:
queue.extend(node['children'])
sub_node_ids.pop(0)
return sub_node_ids