Leetcode 530. Minimum Absolute Difference in BST
程序员文章站
2022-03-04 19:01:10
...
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
/**
* 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) {
vector<int> values;
inOrderTranverse(root, values);
int min = INT_MAX;
for(int i = 1; i < values.size(); i++) {
int diff = values[i] - values[i - 1];
if(min > diff) {
min = diff;
}
}
return min;
}
private:
void inOrderTranverse(TreeNode* root, vector<int>& values) {
if(!root) {
return;
}
if(root->left) {
inOrderTranverse(root->left, values);
}
values.push_back(root->val);
if(root->right) {
inOrderTranverse(root->right, values);
}
}
};
- Version 2
/**
* 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 min = INT_MAX;
int current = -1;
inOrderTranverse(root, min, current);
return min;
}
private:
void inOrderTranverse(TreeNode* root, int& min, int& current) {
if(!root) {
return;
}
if(root->left) {
inOrderTranverse(root->left, min, current);
}
if(current != -1) {
if(min > root->val - current) {
min = root->val - current;
}
}
current = root->val;
if(root->right) {
inOrderTranverse(root->right, min, current);
}
}
};
Reference
推荐阅读
-
LeetCode --- 783. Minimum Distance Between BST Nodes 解题分析
-
LeetCode --- 783. Minimum Distance Between BST Nodes 解题分析
-
530. Minimum Absolute Difference in BST
-
Leetcode每日一题:530.minimum-absolute-difference-in-bst(二叉搜索树的最小绝对值)
-
530. Minimum Absolute Difference in BST
-
LC-Minimum Absolute Difference in BST
-
(Java)leetcode-530 Minimum Absolute Difference in BST (二叉搜索树的最小绝对差)
-
LeetCode之路:530. Minimum Absolute Difference in BST
-
530 - 二叉搜索树的最小绝对差(minimum-absolute-difference-in-bst)
-
530. Minimum Absolute Difference in BST