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

Python运行LeetCode递归代码报isSubtree属性错误求解

问题背景

学习Python二叉树相关递归操作时,在本地PyCharm环境运行LeetCode平台的isSubtree(判断二叉树子树)题解代码,触发如下属性报错:

Traceback (most recent call last):
  File "LCPattern.py", line 55, in <module>
    a = Solution.isSubtree(self, t3,t4)
  File "LCPattern.py", line 39, in isSubtree
    return bool(s and t) and (is_the_same(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t))
AttributeError: 'function' object has no attribute 'isSubtree'
错误原因

报错根源有两处:

  • 类实例方法调用方式错误:直接用类名.方法名()的方式调用实例方法时,没有传入合法的实例对象作为self参数,传入的self在全局作用域下不存在,实际传入的是函数对象本身,导致递归时找不到isSubtree属性。
  • 运行环境差异:LeetCode平台会自动处理类实例化、方法调用的流程,本地运行时需要自己遵循Python类方法的调用规则。
正确调用方法

步骤1:补全TreeNode类定义

本地运行缺少LeetCode内置的二叉树节点类,需要先自行定义:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

步骤2:实例化Solution类后调用方法

不要直接用类名调用实例方法,先创建Solution的实例对象,再通过实例调用isSubtree方法,修正后的完整可运行代码如下:

# 二叉树节点定义
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:

        def is_the_same(s, t):
            if not s and not t:
                return True
            elif s and t:
                return s.val == t.val and is_the_same(s.left, t.left) and is_the_same(s.right, t.right)
            else:
                return False

        return bool(s and t) and (is_the_same(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t))

# 构造测试用例
t3 = TreeNode(3)
t3.left = TreeNode(4)
t3.right = TreeNode(5)
t3.left.left = TreeNode(1)
t3.left.right = TreeNode(2)

t4 = TreeNode(4)
t4.left = TreeNode(1)
t4.right = TreeNode(2)

# 正确调用写法
sol = Solution()
a = sol.isSubtree(t3, t4)
print(a)

运行后输出结果为True,符合预期。

可选调用方式(不推荐)

如果一定要用类名直接调用方法,需要手动把实例对象作为第一个参数传入,该写法不符合常规实例方法调用规范:

sol = Solution()
a = Solution.isSubtree(sol, t3, t4)

内容的提问来源于stack exchange,提问作者Jenny Lian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:45:39