-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path530_minAbsDiffInBST.cpp
More file actions
45 lines (40 loc) · 984 Bytes
/
Copy path530_minAbsDiffInBST.cpp
File metadata and controls
45 lines (40 loc) · 984 Bytes
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> travel(TreeNode* root)
{
vector<int> res;
if (root == NULL)
return res;
res = travel(root->left);
res.push_back(root->val);
vector<int> rightChildren = travel(root->right);
res.insert( res.end(), rightChildren.begin(), rightChildren.end() );
return res;
}
int getMinimumDifference(TreeNode* root) {
vector<int> nums = travel(root);
if (nums.size()<2)
return -1; // shouldn't reach here
int res=abs(nums[1]-nums[0]);
for (size_t i=1; i<nums.size(); ++i)
{
res = min(res, abs(nums[i]-nums[i-1]));
}
return res;
}
};
int main()
{
Solution solution;
return 0;
}