Skip to content

Commit 342f8d8

Browse files
committed
Refactor kthSmallest to use the nonlocal keyword for tracking the result
1 parent 24ba0c6 commit 342f8d8

1 file changed

Lines changed: 4 additions & 7 deletions

File tree

kth-smallest-element-in-a-bst/doh6077.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,16 @@ class Solution:
88
# Time Complexity O(N)
99
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
1010
ans = []
11-
final = [0]
12-
11+
final = 0
1312
def dfs(node):
14-
13+
nonlocal final
1514
if not node:
1615
return
17-
1816
dfs(node.left)
19-
2017
ans.append(node.val)
2118
if len(ans) == k:
22-
final[0] = node.val
19+
final = node.val
2320
if len(ans) < k:
2421
dfs(node.right)
2522
dfs(root)
26-
return final[0]
23+
return final

0 commit comments

Comments
 (0)