我有一个包含两个属性“名称”和“子级”的基本类。
class Node():
def __init__(self, name):
self.name = name
self.children = []
我有一个核心根节点,如下所示:
# Create Master Root Node
root = Node('root')
我将如何创建一个函数,该函数可以将路径传递到树中的特定节点,然后该函数返回该节点。但是,如果该节点不存在,它将创建/追加到树上,并仍然返回该节点。
path = ['Leslie','Marie','Tori'] # simple example
def get_node_by_path(path=[])...
如果路径在到达路径末尾之前发生故障,它将自动创建丢失的节点,以使整个路径完整。
path = ['Leslie','Marie','Tori','Kevin'] # more complex requires two nodes to be created
def get_node_by_path(path=[])...
我会做这样的事情。这是一个非递归的解决方案。
def get_node_by_path(path):
cur_node = root
for elem_name in path:
found = False
for child in cur_node.children:
if child.name == elem_name:
cur_node = child
found = True
break
if not found:
new_node = Node(elem_name)
cur_node.children.append(new_node)
cur_node = new_node
return cur_node
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句