繁体   English   中英

如何在python中替换n元树中的节点?

[英]How to replace a node in an n-ary tree in python?

我使用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)

在替换函数中,节点是我想在以“root”为根的树中替换的新“节点”。

上面的代码不会替换节点。 在替换功能之前和之后,树是相同的。

任何帮助表示赞赏!

如果datachildTree对象的唯一字段,那么在这种情况下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)

但前者更像 Pythonic。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM