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.