给定一个确定根的二叉搜索树,返回树中任意两个不同节点的值的最小差。
样例
样例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
*/
int minDiffInBST(TreeNode * root) {
// Write your code here
recursion(root);
int res=tmp[1]-tmp[0];
for (int i = 1; i < tmp.size(); i++) {
/* code */
res=res<tmp[i]-tmp[i-1]?res:tmp[i]-tmp[i-1];
}
return res;
}
void recursion(TreeNode*root)
{
if(root==NULL) return;
if(root->left)recursion(root->left);
tmp.push_back(root->val);
if(root->right)recursion(root->right);
}
std::vector<int> tmp;
};