给定一个二叉搜索树的根结点 root
, 返回树中任意两节点的差的最小值。
示例:
输入: root = [4,2,6,1,3,null,null] 输出: 1 解释: 注意,root是树结点对象(TreeNode object),而不是数组。 给定的树 [4,2,6,1,3,null,null] 可表示为下图: 4 / \ 2 6 / \ 1 3 最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
注意:
- 二叉树的大小范围在
2
到100
。 - 二叉树总是有效的,每个节点的值都是整数,且不重复。
思路:这道题和Minimum Absolute Difference in 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:
void getMinimumDifferenceCore(TreeNode* root,int &lastValue,int &res) {
if (!root) return;
if (root->left) getMinimumDifferenceCore(root->left, lastValue, res);
if (lastValue!=INT_MIN) res = min(root->val-lastValue,res);
lastValue = root->val;
if (root->right) getMinimumDifferenceCore(root->right, lastValue, res);
}
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
int lastValue = -10000;
getMinimumDifferenceCore(root, lastValue, res);
return res;
}
};