Consider a simple situation such as finding the k'th smallest element in a BST.
In my solution below:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
i = 0
ans = -1
def traverse_inorder(root):
nonlocal i
nonlocal ans
if not root:
return
traverse_inorder(root.left)
i += 1
if i == k:
ans = root.val
return
traverse_inorder(root.right)
traverse_inorder(root)
return ans
Is my use of nonlocal for i and ans good practice? I do this to keep track of how many elements I've traversed after reaching the left most node (smallest value).
Another solution would be to have i and ans as member variables of the class:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.i = 0
self.ans = -1
def traverse_inorder(root):
# etc etc
Are both methods equivalent? Is one practice better than the other, and why?