You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归构建字典树时,不同TreeNode对象的next_nodes为何ID相同?

问题原因及修复方案

你遇到的问题核心是Python类的可变默认参数陷阱:

TreeNode类的__init__方法里,next_nodes的默认值设为[](可变列表)。Python中,类的默认参数是在类定义的时候就创建完成,而不是每次实例化对象时重新生成。这就导致所有没有显式传入next_nodes参数的TreeNode实例,都会共享同一个列表对象——所以你打印的ID完全相同,本质上是同一个列表被所有实例共用了。

修复方法

把默认参数改成None,然后在__init__内部创建新的空列表,确保每个实例都拥有独立的next_nodes:

mydict = {'1': ['21', '22', '23', '24'],
 '21': ['211'],
 '22': ['221', '222'],
 '24': ['241', '242', '243']}

class TreeNode():
    def __init__(self, val = '0', next_nodes = None):
        self.val = val
        # 如果没有传入next_nodes,就新建一个空列表
        self.next_nodes = next_nodes if next_nodes is not None else []

root = TreeNode('1')
def decode(root):
    if root.val not in mydict:
        return None 
    for node_val in mydict[root.val]:
        node = TreeNode(node_val)
        print(id(root.next_nodes), id(node.next_nodes))
        root.next_nodes.append(node)
        decode(node)
decode(root)

这样修改后,每个TreeNode实例的next_nodes都是独立的列表,ID就不会重复了,树形结构的重建也能正常工作。

内容的提问来源于stack exchange,提问作者栋梁彭

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:45:44