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.