我正在學習如何在 python 中執行二叉樹函式,其中大部分是遞回的,所以我嘗試在我的 pycharm 中本地運行一些 leetcode 解決方案,結果卻遇到了這個錯誤:
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'
代碼是
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def is_the_same(s, t):
if not s and not t:
# both s and t are empty
return True
elif s and t:
# both s and t are non-empty
# keep checking in DFS
return s.val == t.val and is_the_same(s.left, t.left) and is_the_same(s.right, t.right)
else:
# one is empty, the other is non-empty
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)
a = Solution.isSubtree(self, t3,t4)
print(a)
顯然 self.isSubtree(s.left, t)是導致此錯誤的原因。有人可以幫我理解如何在本地正確呼叫這些遞回函式嗎?
uj5u.com熱心網友回復:
您以錯誤的方式創建物件-更改此-
a = Solution.isSubtree(self, t3,t4)
至此
a = Solution()
a.isSubtree(t3,t4)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495651.html
標籤:Python python-3.x 递归
上一篇:可變引數模板函式中的靜態變數
下一篇:立即回傳遞回呼叫
