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