Leetcode 530. Minimum Absolute Difference in BST
Given a Binary Search Tree (BST), write a function that returns the minimum absolute difference between the values of any two nodes in the tree.
In-order Traversal: Since an in-order traversal of a BST will give a sorted list of values, the minimum absolute difference would occur between two consecutive elements in this sorted list.
Keep Track of Differences: Traverse the tree in an in-order manner and keep track of the previous node’s value to compute the difference with the current node’s value.
Update the Minimum Difference: Continuously update the minimum difference encountered during traversal.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int min_diff = INT_MAX;
int prev_val = -1; // Indicator for non-existent previous value
inOrderTraversal(root, prev_val, min_diff);
return min_diff;
}
private:
void inOrderTraversal(TreeNode* node, int &prev_val, int &min_diff) {
if (!node) return;
// Traverse left subtree
inOrderTraversal(node->left, prev_val, min_diff);
// Process current node
if (prev_val != -1) {
min_diff = min(min_diff, node->val - prev_val);
}
prev_val = node->val;
// Traverse right subtree
inOrderTraversal(node->right, prev_val, min_diff);
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?