给定一个确定根的二叉搜索树,返回树中任意两个不同节点的值的最小差。
样例
样例1:
输入: root = {4,2,6,1,3,#,#}
输出: 1
解释:
请留意,root是一个树节点的结构,而非一个普通数组。
给定的树{4,2,6,1,3,#,#}的样子如下图:
4
/ \
2 6
/ \
1 3
在这棵树中,最小数值差距为 1, 它出现在node 1 与 node 2 之间, 也同时存在 node 3 与 node 2之间
样例2:
输入: root = {5,1,8}
输出: 3
解释:
请留意,root是一个树节点的结构,而非一个普通数组。
给定的树{5,1,8}的样子如下图:
5
/ \
1 8
在这棵树中,最小数值差距为 3, 它出现在node 5与node 8之间.
注意事项
1.这棵二叉搜索树的大小在 2 到100
之间。
2.这棵二叉搜索树是存在的,每个点的数值是一个整数,而且每个点的数值将会是不同的。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root
* @return: the minimum difference between the values of any two different nodes in the tree
*/
vector<int> nums;
int minDiffInBST(TreeNode * root) {
// Write your code here
bianli(root);
int ret = INT_MAX;
sort(nums.begin(), nums.end());
for(int i = 1; i < nums.size(); i++)
{
ret = min(ret, nums[i] - nums[i-1]);
}
return ret;
}
void bianli(TreeNode* root)
{
if(root != NULL)
{
nums.push_back(root->val);
bianli(root->left);
bianli(root->right);
}
}
};
来源:https://blog.csdn.net/weixin_41791402/article/details/99693662