I tried to test a leetcode solution on my local PC (WSL, python3) to have a better understanding of the problem
from https://leetcode.com/problems/same-tree/discuss/2594714/python-recurse-in-same-function I modified it as
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
elif (p and not q) or (q and not p):
return False
return (
self.isSameTree(p.left, q.left) and
(p.val == q.val) and
self.isSameTree(p.right, q.right)
)
print(Solution.isSameTree([1,2,3],[1,2,3]))
I got (binary_tree.py
is the name of the file for the above code)
Traceback (most recent call last):
File "binary_tree.py", line 24, in <module>
print(Solution.isSameTree([1,2,3],[1,2,3]))
TypeError: isSameTree() missing 1 required positional argument: 'q'
Seems I have a very basic issue in using python class. But, what is the problem and how to fix it?
CodePudding user response:
TLDR
You need to instantiate the Solution
class instance before calling the class function. i.e.,
solution = Solution()
tree1 = TreeNode(1, TreeNode(2), TreeNode(3))
tree2 = TreeNode(1, TreeNode(2), TreeNode(3))
print(solution.isSameTree(tree1, tree2))
Or, you should add @classmethod
or @staticmethod
decorator on the isSameTree
function.
Explanation
The error stack told you that TypeError: isSameTree() missing 1 required positional argument: 'q'
. In other words. isSameTree()
needs three required arguments while you only pass two of them(self
, p
). The first list of your arguments is considered as a self
.
By instantiating a Solution
class instance, calling with it will pass self
as an argument automatically. Or you can add @classmethod
to pass cls
automatically without instantiating a class instance. @staticmethod
has similar effect but works differently. Check answers under this question for more information:
Difference between @staticmethod and @classmethod
Also, passing lists into isSameTree
doesn't work either. You should build TreeNode
s by TreeNode
class.