Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中替换n元树中的节点?_Python_Python 3.x_Tree - Fatal编程技术网

如何在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

我已经使用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 == 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)
但前者更像蟒蛇