-
Notifications
You must be signed in to change notification settings - Fork 1
/
530-Minimum-Absolute-Difference-in-BST.cpp
62 lines (48 loc) · 1.51 KB
/
530-Minimum-Absolute-Difference-in-BST.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* 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 getMinimumDifference(TreeNode* root) {
int ans = INT_MAX;
vector<int> vals;
traverse(root, vals);
std::sort(vals.begin(), vals.end());
for(int i = 0; i < vals.size()-1; i++){
if(vals[i+1] - vals[i] < ans) ans = vals[i+1] - vals[i];
}
return ans;
}
void traverse(TreeNode* node, vector<int>& vals){
if(node->left != nullptr) traverse(node->left, vals);
if(node->right != nullptr) traverse(node->right, vals);
vals.push_back(node->val);
}
};
/* 530. Minimum-Absolute-Difference-in-BST.cpp
//////////////////////////////////////////////////
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note:
There are at least two nodes in this BST.
https://leetcode.com/problems/minimum-absolute-difference-in-bst/
//////////////////////////////////////////////////
*/