NameError : variable not defined
NameError : variable not defined
对于简单的混淆,我们深表歉意。变量 'head' 已在使用全局引用的方法中被提及。但事实并非如此!
这是我的代码:
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
使用__init__
魔术方法,并声明那些class实例变量,self
(实例)是它的对象分配给 (self
实际上是 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
对于简单的混淆,我们深表歉意。变量 'head' 已在使用全局引用的方法中被提及。但事实并非如此!
这是我的代码:
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
使用__init__
魔术方法,并声明那些class实例变量,self
(实例)是它的对象分配给 (self
实际上是 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