-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0530_minimum-absolute-difference-in-bst.cpp
More file actions
46 lines (42 loc) · 1.13 KB
/
Copy path0530_minimum-absolute-difference-in-bst.cpp
File metadata and controls
46 lines (42 loc) · 1.13 KB
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
/**
* 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) {
// bfs
vector<int> d;
queue<TreeNode *> q;
q.emplace(root);
while (!q.empty()) {
auto top = q.front();
if (top == nullptr) {
continue;
}
q.pop();
d.emplace_back(top->val);
if (top->left)
q.emplace(top->left);
if (top->right)
q.emplace(top->right);
}
// find minimum difference
int n = d.size();
int ret = numeric_limits<int>::max();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
ret = min(ret, abs(d[i] - d[j]));
}
}
return ret;
}
};