530. Minimum Absolute Difference in BST
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the minimum absolute difference between the values of any two distinct nodes in a Binary Search Tree (BST). A brute-force approach would be to compare every pair of nodes, which would take O(N^2) time, where N is the number of nodes. Given the constraints (N up to 10^4), this would be too slow.
Solution
Minimum Absolute Difference in BST in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
# Initialize min_diff to positive infinity.
self.min_diff = float('inf')
# To store the value of the previously visited node.
self.prev_val = None
self.inorder_traversal(root)
return self.min_diff
def inorder_traversal(self, node: Optional[TreeNode]):
if not node:
return
# 1. Traverse the left subtree
self.inorder_traversal(node.left)
# 2. Process the current node
if self.prev_val is not None:
# Calculate difference with the previous node's value
self.min_diff = min(self.min_diff, node.val - self.prev_val)
# Update the previous value to the current node's value
self.prev_val = node.val
# 3. Traverse the right subtree
self.inorder_traversal(node.right)
Minimum Absolute Difference in BST in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// To store the minimum difference found so far.
private int minDifference = Integer.MAX_VALUE;
// To store the value of the previously visited node in the in-order traversal.
// Using Integer wrapper class allows it to be null for the first node.
private Integer prevValue = null;
public int getMinimumDifference(TreeNode root) {
inorderTraversal(root);
return minDifference;
}
private void inorderTraversal(TreeNode node) {
if (node == null) {
return;
}
// 1. Traverse the left subtree
inorderTraversal(node.left);
// 2. Process the current node
if (prevValue != null) {
// If it's not the first node, calculate the difference
minDifference = Math.min(minDifference, node.val - prevValue);
}
// Update prevValue to the current node's value for the next iteration
prevValue = node.val;
// 3. Traverse the right subtree
inorderTraversal(node.right);
}
}
Minimum Absolute Difference in BST in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int minDifference = INT_MAX;
// Use a pointer to the previous node to handle the first node case gracefully.
TreeNode* prevNode = nullptr;
public:
int getMinimumDifference(TreeNode* root) {
inorderTraversal(root);
return minDifference;
}
void inorderTraversal(TreeNode* node) {
if (node == nullptr) {
return;
}
// 1. Traverse the left subtree
inorderTraversal(node->left);
// 2. Process the current node
if (prevNode != nullptr) {
// If it's not the first node, calculate the difference with the previous node
minDifference = std::min(minDifference, node->val - prevNode->val);
}
// Update prevNode to the current node for the next iteration
prevNode = node;
// 3. Traverse the right subtree
inorderTraversal(node->right);
}
};
Minimum Absolute Difference in BST in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function getMinimumDifference(root: TreeNode | null): number {
let minDiff = Infinity;
let prevVal: number | null = null;
function inorder(node: TreeNode | null) {
if (node === null) {
return;
}
// 1. Traverse the left subtree
inorder(node.left);
// 2. Process the current node
if (prevVal !== null) {
// If it's not the first node, calculate the difference
minDiff = Math.min(minDiff, node.val - prevVal);
}
// Update prevVal for the next node in the traversal
prevVal = node.val;
// 3. Traverse the right subtree
inorder(node.right);
}
inorder(root);
return minDiff;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.