↓Skip to main content
  1. LeetCode/

LeetCode 530: Minimum Absolute Difference in BST

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Search-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted ×2

Approach
#

A BST’s in-order traversal is sorted, and in a sorted sequence the closest pair is adjacent (Tree Template 3). Remember the previous value during the in-order walk and update the answer with each difference. This is the same problem as LC 783.

My Solution
#

class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        best, prev = float("inf"), None
        stack, cur = [], root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            if prev is not None:
                best = min(best, cur.val - prev)
            prev = cur.val
            cur = cur.right
        return best

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • The closest values need not be parent and child; compare in-order neighbors.

Interview Explanation
#

A BST’s in-order is sorted and the minimum difference lies between neighbors, so I keep the previous value during the in-order walk and update the minimum. Time O(n).

Related

LeetCode 501: Find Mode in Binary Search Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 note: a BST’s in-order is sorted, so equal values are contiguous; count the current run during in-order, resetting the answer on a new maximum and appending on a tie
LeetCode 404: Sum of Left Leaves
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 note: tell each child during DFS whether it is a left child, adding only left children that are leaves
LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum
LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf
LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides