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.
这道题是找二叉搜索树中任意两节点之间的最小绝对差,题目难度为Easy。
我们知道按中序遍历BST得到的节点值是递增的,题目限定BST中所有节点值非负,因此只需要比较中序遍历时所有相邻节点的绝对差即可得到最小绝对差。这样题目就变成了中序遍历二叉树的问题,大家可以顺便看下第94题(传送门)和第145题(传送门)。
遍历二叉树可以通过递归和非递归两种方法,递归的方法比较简单,不再详细说明,具体代码:
class Solution {
void inorder(TreeNode* p, int& minDiff, int& pre) {
if(p->left) inorder(p->left, minDiff, pre);
if(pre != -1) minDiff = min(minDiff, p->val - pre);
pre = p->val;
if(p->right) inorder(p->right, minDiff, pre);
}
public:
int getMinimumDifference(TreeNode* root) {
int minDiff = INT_MAX, pre = -1;
inorder(root, minDiff, pre);
return minDiff;
}
};
非递归的方法需要借助栈来记录遍历路径上的节点,具体说明请查看第145题(传送门)的详细说明, 具体代码:
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int minDiff = INT_MAX, pre = -1;
stack<TreeNode*> stk;
TreeNode* p = root;
while(p || !stk.empty()) {
while(p) {
stk.push(p);
p = p->left;
}
p = stk.top();
stk.pop();
if(pre != -1) minDiff = min(minDiff, p->val - pre);
pre = p->val;
p = p->right;
}
return minDiff;
}
};