Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 530 · Tree

Minimum Absolute Difference in BST

LeetCode 530 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

In-order with a previous-node pointer.

ಸುಲಭTreeDepth-First SearchBreadth-First SearchBinary Search TreeBinary Tree
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    In-order DFS.

  2. 2

    If there is a previous node, update min with the gap.

  3. 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.mn
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Minimum 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.