给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
\
3
/
2
输出:
1
解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
提示:
树中至少有 2 个节点。
本题与 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ 相同
解题思路:
原谅我看错了题目,看成了普通的二叉树,于是奇思妙想决定把所有的值取出来排序,然后循环遍历得出结果,果然是对的,但是击败率惨不忍睹,代码如下:
/**
* 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:
int getMinimumDifference(TreeNode* root) {
if(root->left == NULL && root->right == NULL){
return abs(root->val);
}
vector<int> ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
for(int i = 0 ; i < size; i ++){
TreeNode * temp = q.front();
q.pop();
ans.push_back(temp->val);
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
sort(ans.begin(),ans.end());
int min = 1000000;
for(int i = 0 ; i < ans.size() - 1; i ++){
for(int j = i + 1; j < ans.size(); j ++){
int res = ans[j] - ans[i];
if(res < min){
min = res;
}
}
}
return min;
}
};
中序遍历是个好东西,在遍历的过程中,就是从小到大的过程,那么比较一下就可以得出结果了,代码如下:
class Solution {
public:
void dfs(TreeNode* root, int& pre, int& ans) {
if (root == nullptr) {
return;
}
dfs(root->left, pre, ans);
if (pre == -1) {
pre = root->val;
} else {
ans = min(ans, root->val - pre);
pre = root->val;
}
dfs(root->right, pre, ans);
}
int getMinimumDifference(TreeNode* root) {
int ans = INT_MAX, pre = -1;
dfs(root, pre, ans);
return ans;
}
};