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