We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 1bbdd53 commit 48f3cbdCopy full SHA for 48f3cbd
kth-smallest-element-in-a-bst/yolophg.py
@@ -0,0 +1,21 @@
1
+# Time Complexity: O(N) - visit each node once in an inorder traversal.
2
+# Space Complexity: O(N) - store all node values in a list.
3
+
4
+class Solution:
5
+ def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
6
+ def inorder(node):
7
+ if not node:
8
+ return
9
10
+ # go left (smaller values first)
11
+ inorder(node.left)
12
+ # add the current node's value
13
+ values.append(node.val)
14
+ # go right (larger values next)
15
+ inorder(node.right)
16
17
+ values = []
18
+ inorder(root)
19
20
+ # get the k-th smallest element (1-based index)
21
+ return values[k - 1]
0 commit comments