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).