Leetcode 783. Minimum Distance Between BST Nodes
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
#include <climits> // For INT_MAX
#include <algorithm> // For std::min
// 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 {
public:
int minDiffInBST(TreeNode* root) {
int minDiff = INT_MAX;
int prev = -1; // Initialize prev with a value that won't be in the BST (assuming BST values are positive).
// Helper function for inorder traversal
void inorder(TreeNode* node) {
if (!node) return;
inorder(node->left);
if (prev != -1) { // If prev has been updated at least once
minDiff = std::min(minDiff, node->val - prev);
}
prev = node->val;
inorder(node->right);
}
inorder(root);
return minDiff;
}
};
This approach ensures we correctly find the minimum distance between any two nodes in the BST by leveraging properties of inorder traversal resulting in a sorted sequence.
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?