python - 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 递归地包含自身。我错过了哪些点?
解决方案
我已经找到了解决方案并分享了具有类似解决方案的解决方案。init 函数中的行
self.child_nodes = child_nodes
结果导致我将其更改为
self.child_nodes = []
并删除了参数。问题解决了。
推荐阅读
- java - 使用多线程的消费者-生产者问题
- sql - BigQuery:进行交叉连接并添加另一个要分区的字段时的额外行
- dataframe - 在 Dataframe Pyspark 中添加对数列
- javascript - 在 JavaScript 中用新替换旧
- javascript - Ext Js 中的另存为对话框
- python - 所有测试的python补丁
- vba - 在工作表 VBA 中编辑插入行功能
- xslt - xslt/saxon - 将 key() 与 collection() 一起使用:prolog 中不允许内容?
- android-tv - Searchable Android AppTv 上的 SQL 注入漏洞
- enterprise-architect - sparx Enterprise Architect BPMN 步入和退出子模型(复合模型)