[LeetCode] Minimum Absolute Difference in BST

530. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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:
void dfs(TreeNode* node, vector<int>& A) {
A.push_back(node->val);
if(node->left) {
dfs(node->left, A);
}
if(node->right) {
dfs(node->right, A);
}
}
int getMinimumDifference(TreeNode* root) {
int res = INT_MAX;
vector<int> A;
dfs(root,A);
sort(begin(A), end(A));
for(int i = 0; i < A.size() - 1; i++) res = min(res, A[i+1] - A[i]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/14/PS/LeetCode/minimum-absolute-difference-in-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.