Search code examples
pythonnameerror

NameError : variable not defined


Sorry for the simple confusion. The variable 'head' has been mentioned inside the method using a global reference. But it's not!

Here is my code:

class Solution:
    head = None
    current = None
    def constructMaximumBinaryTree(self, nums: List[int]) -> 
TreeNode:
        m = nums.index(max(nums))
        global head
        global current
        if not head:
            head = TreeNode()
            head.val = max(nums)
            head.left = constructMaximumBinaryTree(self, nums[:m])
            head.right = constructMaximumBinaryTree(self, nums[m + 1:])
        elif not current:
            current = head
        else:
            pass
        current.left = constructMaximumBinaryTree(self, nums[:m])
        current.right = constructMaximumBinaryTree(self, nums[m+1:])
        return head

Solution

  • Use an __init__ magic method, and declare those class instance variables, with self (the instance) being the object it's assigning to (self is virtually the class):

    class Solution:
        def __init__(self):
            self.head = None
            self.current = None
        def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
            m = nums.index(max(nums))
            if not self.head:
                self.head = TreeNode()
                self.head.val = max(nums)
                self.head.left = constructMaximumBinaryTree(self, nums[:m])
                self.head.right = constructMaximumBinaryTree(self, nums[m + 1:])
            elif not current:
                current = self.head
            else:
                pass
            current.left = constructMaximumBinaryTree(self, nums[:m])
            current.right = constructMaximumBinaryTree(self, nums[m+1:])
            return self.head