首页 > 解决方案 > Python树数据类型在递归子代中添加子操作结果

问题描述

我有一个在 python 中生成的树,我只是想将一个新的子节点附加到父节点,但是,虽然子节点的子节点是空的,但似乎子节点成为父节点和自身的子节点。

def __init__(self):
    self.child_nodes = []
    self.data = None
    ...
    self.parent = None

def init_tree(self, data, child_nodes=[], ...):
    self.child_nodes = child_nodes
    self.data = data
    ...

def add_child_node(self, node):
    ancestors = self.get_ancestors()
    if node is not self and node not in ancestors:
        self.child_nodes.append(node)
        node.parent = self

def get_ancestors(self):
    ancestor = self.parent
    ancestors = [ancestor]
    try:
        while ancestor.parent != None:
            ancestors.append(ancestor)
            parent = self.parent
            ancestor = parent.get_parent()
        return ancestors
    # Node is root. Root's parent is None
    except AttributeError:
        return []


def my_funct(self):
    ...
    child_node = RandomWalkTree()       
    child_node.init_tree(data=data)
    self.add_child_node(child_node)

my_funct 产生一个子节点,其 child_nodes 递归地包含自身。我错过了哪些点?

标签: pythonpython-2.7recursiondata-structurestree

解决方案


我已经找到了解决方案并分享了具有类似解决方案的解决方案。init 函数中的行

self.child_nodes = child_nodes

结果导致我将其更改为

self.child_nodes = [] 

并删除了参数。问题解决了。


推荐阅读