[leetcode-530-Minimum Absolute Difference in BST]

时间:2023-03-09 04:32:16
[leetcode-530-Minimum Absolute Difference in BST]

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

思路:

中序遍历能得到有序数列,而且最小差一定出现在相邻元素。

void zhongxubianli(TreeNode* root, vector<int>& tree)
{
if (root!=NULL)
{
zhongxubianli(root->left, tree);
tree.push_back(root->val);
zhongxubianli(root->right, tree);
}
}
int getMinimumDifference(TreeNode* root)
{
vector<int>tree;
zhongxubianli(root, tree);
int ret = ;
for (int i = ; i < tree.size();i++)
{
ret = min(ret, tree[i] - tree[i - ]);
}
return ret;
}
     void zhongxubianli(TreeNode* root, int& ret,int& temp)
{
if (root!=NULL)
{
zhongxubianli(root->left, ret,temp);
if(temp>=)ret = min(ret, root->val - temp);
temp = root->val;
zhongxubianli(root->right, ret,temp);
}
}
int getMinimumDifference(TreeNode* root)
{
int ret = ,temp = -;
zhongxubianli(root, ret,temp);
return ret;
}