I am working on a self-defined class to solve the problem, which is pretty common format in leetcode. The problem is as:
Path with Maximum Sum (hard) # Find the path with the maximum sum in a
given binary tree. Write a function that returns the maximum sum. A
path can be defined as a sequence of nodes between any two nodes and
doesn’t necessarily pass through the root.
My approach is:
class Solution:
def __inti__(self):
self.maxSum = 0
def sumMax(self, root):
# self.maxSum = 0
self.findSum(root)
return self.maxSum
def findSum(self, root):
if not root:
return 0
l = self.findSum(root.left)
r = self.findSum(root.right)
tempMax = l + r + root.value
if tempMax > self.maxSum:
self.maxSum = tempMax
# self.maxSum = max(self.maxSum, tempMax)
return max(l, r) + root.value
class TreeNode:
def __init__(self, _value):
self.value = _value
self.left, self.right, self.next = None, None, None
def main():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
print(Solution().sumMax(root))
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
root.right.left.left = TreeNode(7)
root.right.left.right = TreeNode(8)
root.right.right.left = TreeNode(9)
print(Solution().sumMax(root))
main()
which will return error message as:
Traceback (most recent call last):
File "/Users/tairanye/PycharmProjects/tester/main.py", line 46, in <module>
main()
File "/Users/tairanye/PycharmProjects/tester/main.py", line 33, in main
print(Solution().sumMax(root))
File "/Users/tairanye/PycharmProjects/tester/main.py", line 7, in sumMax
self.findSum(root)
File "/Users/tairanye/PycharmProjects/tester/main.py", line 13, in findSum
l = self.findSum(root.left)
File "/Users/tairanye/PycharmProjects/tester/main.py", line 13, in findSum
l = self.findSum(root.left)
File "/Users/tairanye/PycharmProjects/tester/main.py", line 16, in findSum
if tempMax > self.maxSum:
AttributeError: 'Solution' object has no attribute 'maxSum'
Process finished with exit code 1
I think I follow the correct fashion, but not sure why this error happened. I can fix this error by inserting self.maxSum = 0
in my sumMax
function, but I am not sure why my previous approach is not working. The Python version is 3.8
.
Thank you for your help in advance.
The typo made this error. But I have further question. Why did Python accept the misspelled __inti__
without a notification. I don't think it has this command as default. Thanks.
question from:
https://stackoverflow.com/questions/65713175/self-defined-class-issue-attributeerror-xx-object-has-no-attribute-xx 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…