[Python]Question on class?


  • 3
    Z
    class Solution:
        # @param root, a tree node
        # @return an integer
        def maxsum(self, root):
            if root == None: 
                return 0
            sum = root.val
            lmax = self.maxsum(root.left)
            rmax = self.maxsum(root.right)
            if lmax > 0: sum += lmax;
            if rmax > 0: sum += rmax;
            Solution.max = max(Solution.max, sum)
            return max(root.val, max(root.val + lmax, root.val + rmax))
        def maxPathSum(self, root):
            Solution.max = -10000000
            if root == None: 
                return 0
            self.maxsum(root)
            return Solution.max
    

    I was trying to set variable name Solution.max to max or best before, but OJ said variable doesn't define. It only works when Solution. something. Is it because of class name? Could someone explain to me? Thanks in advance!


  • 2

    When you declare max = 3, you are declaring a local variable.

    When you declare Solution.max = 3, you are declaring a class variable.

    Local variable only has the scope within a method.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.