Kth Smallest Element in a BST
LeetCode 230 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
In-order traversal → index k−1.
मी Kth Smallest Element in a BST (LeetCode 230) असा सोडवला — BST पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.
Approach
- 1
In-order DFS into a list.
- 2
Return arr[k − 1].
मी कसा सोडवला
In-order listPythonO(n) time · O(n) space
class Solution:
def kthSmallest(self, root, k):
arr = []
def dfs(node):
if node is None:
return
dfs(node.left)
arr.append(node.val)
dfs(node.right)
dfs(root)
return arr[k - 1]Kth Smallest Element in a BST — वारंवार विचारले जाणारे प्रश्न
Kth Smallest Element in a BST मागील intuition काय आहे?
An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.
Kth Smallest Element in a BST (LeetCode 230) कसा सोडवावा?
1. In-order DFS into a list. 2. Return arr[k − 1].
Kth Smallest Element in a BST ची time आणि space complexity किती आहे?
Time: O(n). Space: O(n). (Accepted approach: In-order list.)
Kth Smallest Element in a BST मध्ये सामान्य चुका कोणत्या?
Stopping the traversal after k nodes makes it O(h + k).