Minimum Absolute Difference in BST
LeetCode 530 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
In-order with a previous-node pointer.
मैंने Minimum Absolute Difference in BST (LeetCode 530) ऐसे हल किया — Tree पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
In-order traversal of a BST visits values in sorted order, and the smallest difference in a sorted list is always between neighbours. Remember the previous node visited and compare.
Approach
- 1
In-order DFS.
- 2
If there is a previous node, update min with the gap.
- 3
Set previous to the current node.
मैंने कैसे हल किया
In-order with prevPythonO(n) time · O(h) space
class Solution:
def getMinimumDifference(self, root):
self.prevNode = None
self.mn = float("inf")
def dfs(node):
if node is None:
return
dfs(node.left)
if self.prevNode is not None:
self.mn = min(self.mn, abs(node.val - self.prevNode.val))
self.prevNode = node
dfs(node.right)
dfs(root)
return self.mnMinimum Absolute Difference in BST — अक्सर पूछे जाने वाले प्रश्न
Minimum Absolute Difference in BST के पीछे intuition क्या है?
In-order traversal of a BST visits values in sorted order, and the smallest difference in a sorted list is always between neighbours. Remember the previous node visited and compare.
Minimum Absolute Difference in BST (LeetCode 530) कैसे हल करें?
1. In-order DFS. 2. If there is a previous node, update min with the gap. 3. Set previous to the current node.
Minimum Absolute Difference in BST की time और space complexity क्या है?
Time: O(n)। Space: O(h)। (Accepted approach: In-order with prev।)
Minimum Absolute Difference in BST में आम गलतियाँ क्या हैं?
Comparing a node only with its children misses neighbours across subtrees.