给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
思路:利用二叉搜索树中序遍历有序的特性,用中序遍历当前值减去前一个值,找到最小的即可。
方法一:递归法
class Solution { //530. 二叉搜索树的最小绝对差 递归法
public:
int result = INT_MAX;
TreeNode* preNode;
void traversal(TreeNode* root) {
if (root == nullptr) return;
traversal(root->left);
if (preNode != nullptr) {
result = min(result, root->val - preNode->val);
}
preNode = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
方法二:迭代法
class Solution { //530. 二叉搜索树的最小绝对差 迭代法
public:
int getMinimumDifference(TreeNode* root) {
int result = INT_MAX;
stack<TreeNode*> stk;
TreeNode* cur = root;
TreeNode* pre = nullptr;
while (cur != nullptr || !stk.empty()) {
if (cur != nullptr) {
stk.push(cur);
cur = cur->left;
}
else {
cur = stk.top();
stk.pop();
if (pre != nullptr) {
result = min(result, cur->val - pre->val);
}
pre = cur;
cur = cur->right;
}
}
return result;
}
};
参考资料:代码随想录