-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_530
38 lines (37 loc) · 1.04 KB
/
leetcode_530
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void in_order(TreeNode* root,vector<int>& sort_list)//参数为前一个数,初始为0
{
if(root->left)
in_order(root->left,sort_list);
sort_list.push_back(root->val);
if(root->right)
in_order(root->right,sort_list);
}
int getMinimumDifference(TreeNode* root) {
//二叉搜索树,中序遍历是排好序的
//故可以用中序遍历,计算相邻数字之间的差值
vector<int> sort_list;
in_order(root,sort_list);
for(int i=0;i<sort_list.size()-1;i++)
{
sort_list[i]=abs(sort_list[i]-sort_list[i+1]);
}
int min=sort_list[0];
for(int i=0;i<sort_list.size()-1;i++)
{
if(sort_list[i]<min)
min=sort_list[i];
}
return min;
}
};