I'm learning how to do binary tree functions in python, most of which are recursive, so I tried to run some leetcode solutions locally in my pycharm only to run into this error:
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'
code is
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)
Apparently self.isSubtree(s.left, t)
is what's causing this error.
Can some one help me understand how to properly call recursive functions like these locally please?
CodePudding user response:
You are creating the object wrong way - Change this -
a = Solution.isSubtree(self, t3,t4)
to This
a = Solution()
a.isSubtree(t3,t4)