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.