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).
Note: There are at least two nodes in this BST.
解法一
思路
既然是要找结点值之间最小的差的绝对值,那就是对每个结点值找到与其最相近的结点值,然后求差了。设想如果是一个有序数组的话,这样的最小值就是按顺序后一个元素与前一个元素的差的最小值了。看到BST第一反应就是BST的中序遍历结果是有序数组,正好对应上了,那就是中序遍历时,求当前结点与前一结点的差,差的最小值就是结果了。
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = sys.maxsize
stack = []
prev = None
while root or stack:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
if prev is not None:
result = min(result, node.val - prev)
prev = node.val
root = node.right
return result
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int getMinimumDifference(TreeNode root) {
int result = Integer.MAX_VALUE;
Stack<TreeNode> stack = new Stack<>();
Integer prev = null;
while (root != null || !stack.empty()) {
if (root != null) {
stack.add(root);
root = root.left;
} else {
TreeNode node = stack.pop();
if (prev != null) {
result = Math.min(result, node.val - prev);
}
prev = node.val;
root = node.right;
}
}
return result;
}
}
C++
/**
* 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 result = INT_MAX;
stack<TreeNode *> sta;
int prev = 0;
bool hasPrev = false;
while (root != nullptr || !sta.empty()) {
if (root != nullptr) {
sta.push(root);
root = root->left;
} else {
TreeNode *node = sta.top();
sta.pop();
if (hasPrev) {
result = min(result, node->val - prev);
}
prev = node->val;
hasPrev = true;
root = node->right;
}
}
return result;
}
};