Leetcode 530: Minimum Absolute Difference in BST

grid47
grid47
Exploring patterns and algorithms
Sep 15, 2024 6 min read

A binary search tree where nodes light up showing the minimum absolute difference between node values.
Solution to LeetCode 530: Minimum Absolute Difference in BST Problem

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a Binary Search Tree, which is represented as a list of integers where each value represents a node in the tree. Null values indicate absent nodes.
Example: Input: root = [4,2,6,1,3]
Constraints:
• 2 <= The number of nodes in the tree <= 10^4
• 0 <= Node.val <= 10^5
Output: Return the smallest absolute difference between values of any two nodes in the tree.
Example: Output: 1
Constraints:
• The answer will always be a positive integer.
Goal: To find the minimum absolute difference between values of any two nodes in the BST.
Steps:
• Perform an in-order traversal of the BST. In-order traversal of a BST yields a sorted list of values.
• For each adjacent pair of values in this sorted list, calculate the absolute difference.
• Track the minimum difference encountered.
Goal: Constraints for this problem ensure that the tree has at least two nodes, and node values are within the valid range.
Steps:
• Node values are non-negative and less than or equal to 10^5.
• The number of nodes in the tree is between 2 and 10^4.
Assumptions:
• The input tree is a valid Binary Search Tree.
• The tree will contain at least two nodes.
Input: Input: root = [4,2,6,1,3]
Explanation: An in-order traversal of the BST gives the values [1, 2, 3, 4, 6]. The minimum absolute difference is 1, as the closest pair is (2, 3).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus