如何在python中替换n元树中的节点?
我已经使用python创建了一个n元树。树结构如下如何在python中替换n元树中的节点?,python,python-3.x,tree,Python,Python 3.x,Tree,我已经使用python创建了一个n元树。树结构如下 class Tree: def __init__(self, data=None): self.data=data self.child=[] 我想替换树中的节点。我使用前序遍历来查找要替换的节点。以下是替换节点的代码 def replace(self, root, node): if root is not None: if root.data == n
class Tree:
def __init__(self, data=None):
self.data=data
self.child=[]
我想替换树中的节点。我使用前序遍历来查找要替换的节点。以下是替换节点的代码
def replace(self, root, node):
if root is not None:
if root.data == node.data:
root=node
root.child=node.child
return
for i in range(0,len(root.child)):
self.replace(root.child[i], node)
在replace函数中,node是我要在根为“root”的树中替换的新“node”
上述代码不会替换节点。替换函数前后,树是相同的
感谢您的帮助 如果
data
和child
是树
对象的唯一字段,那么在这种情况下root.child=node.child
就足够了。所以只需删除root=node
行,因为它只替换局部变量root
另一项说明:
for child in root.child:
self.replace(child, node)
其工作原理与:
for i in range(0,len(root.child)):
self.replace(root.child[i], node)
但前者更像蟒蛇