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).
Note: There are at least two nodes in this BST.
这道题目就是计算任意两个节点的值,计算最小的差。
这里我是使用了中序遍历存储,然后计算最小的值。
代码实现
一开始以为是计算连续两个节点之间的最小值,所以计算错误:
/**
* 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 res = INT_MAX, max = INT_MIN, min = INT_MAX;
int getMinimumDifference(TreeNode* root) {
if(!root) return res;
else {
if(root->left) {
if(abs(root->val - root->left->val) < res) res = abs(root->val - root->left->val);
res = getMinimumDifference(root->left);
}
if(root->right) {
if(abs(root->val - root->right->val) < res) res = abs(root->val - root->right->val);
res = getMinimumDifference(root->right);
}
}
return res;
}
};
然后我使用了中序遍历,就找到了最小的absolute diff。
/**
* 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 getInorder(vector<int>&inque, TreeNode* root) {
if(!root) return;
getInorder(inque, root->left);
inque.push_back(root->val);
getInorder(inque, root->right);
}
int getMinimumDifference(TreeNode* root) {
if(!root) return 0;
vector<int> inOrder;
getInorder(inOrder, root);
int res = INT_MAX;
for(int i = 1, n = inOrder.size(); i < n; i++)
if((inOrder[i] - inOrder[i-1]) < res)
res = inOrder[i] - inOrder[i-1];
return res;
}
};
刚才的方法是递归实现的,需要额外的O(n)的存储。所以这里改成使用非递归的方式,就可以节约不少空间。当然非递归的方式也需要一个栈,但是这个栈相比之前的vector更加节约内存。
/**
* 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) {
int res = INT_MAX;
if(root == NULL) return res;
stack<TreeNode*> sk;
TreeNode* pre = nullptr;
TreeNode* suc = nullptr;
while(true){
// 把左边的节点push进入到栈中
while(root){
sk.push(root);
root = root->left;
}
// 若为空则退出
if(sk.empty()) break;
// 从最左边的子节点开始计算起
root = sk.top();
sk.pop();
suc = (!sk.empty()) ? sk.top() : nullptr;
// 把左边节点与中间节点计算差值
if(pre) res = min(res, abs(root->val - pre->val));
// 计算右边节点与父节点的差值
if(suc) res = min(res, abs(root->val - suc->val));
pre = root;
root = root->right;
}
return res;
}
};