Minimum Absolute Difference in BST 二叉搜索树的最小绝对差

给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。

示例 :

输入:

   1
    \
     3
    /
   2

输出:
1

解释:
最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

注意: 树中至少有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:
void getMinimumDifferenceCore(TreeNode* root,int &lastValue,int &res) {
	if (!root) return;
	if (root->left) getMinimumDifferenceCore(root->left, lastValue, res);
	if (abs(root->val - lastValue) < res) res = (abs(root->val - lastValue));
	lastValue = root->val;
	if (root->right) getMinimumDifferenceCore(root->right, lastValue, res);
}
int getMinimumDifference(TreeNode* root) {
	int res = INT_MAX;
	int lastValue = -10000;
	getMinimumDifferenceCore(root, lastValue,res);
	return res;
}
};

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/83020539