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.