2023-06-14 Daily Challenge
Today I have done leetcode's June LeetCoding Challenge with cpp
.
June LeetCoding Challenge 14
Description
Minimum Absolute Difference in BST
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.
Example 1:
Input: root = [4,2,6,1,3] Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49] Output: 1
Constraints:
- The number of nodes in the tree is in the range
[2, 104]
. 0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Solution
class Solution {
int answer = INT_MAX;
void solve(TreeNode* root, set<int> &st) {
if(!root) return;
if(st.size()) {
auto lessIt = st.upper_bound(root->val);
if(lessIt != st.begin()) {
--lessIt;
answer = min(answer, root->val - *lessIt);
}
auto moreOrEqualIt = st.lower_bound(root->val);
if(moreOrEqualIt != st.end()) {
answer = min(answer, *moreOrEqualIt - root->val);
}
}
st.insert(root->val);
solve(root->left, st);
solve(root->right, st);
}
public:
int getMinimumDifference(TreeNode* root) {
set<int> st;
solve(root, st);
return answer;
}
};
// Accepted
// 188/188 cases passed (27 ms)
// Your runtime beats 30.22 % of cpp submissions
// Your memory usage beats 5.25 % of cpp submissions (29.5 MB)