Reputation: 29
I am getting below error
name i is not defined at line i += 1
I tried putting at class Solution level. Getting same error
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
i = 0
def inOrder(root):
global i
if root == None:
return
inOrder(root.left)
i += 1
if i == k:
return
inOrder(root.right)
inOrder(root)
return i
Upvotes: 0
Views: 58
Reputation: 122
The scopes of kthSmallest
and inOrder
are different.
Without specifying i
as a global variable in kthSmallest
, i
won't be known inside inOrder
.
Nested functions scopes
For nested functions, you need to declare your global variable in the parent function scope as well.
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
global i
i = 0
def inOrder(root):
global i
if root is None:
return
inOrder(root.left)
i += 1
if i == k:
return
inOrder(root.right)
inOrder(root)
return i
Remark 1
It looks like you are using a class in your example. You could also have done the following:
class Solution:
self.i = 0
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.i = 0
def inOrder(root):
if root is None:
return
inOrder(root.left)
self.i += 1
if self.i == k:
return
inOrder(root.right)
inOrder(root)
return i
Upvotes: 0
Reputation: 532418
There is no global i
. The variable you want is in the non-local enclosing scope.
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
i = 0
def inOrder(root):
nonlocal i
if root == None:
return
inOrder(root.left)
i += 1
if i == k:
return
inOrder(root.right)
inOrder(root)
return i
Upvotes: 1