描述
Given a binary search tree with non-negative values, find the minimum absolute differencebetween values of any two nodes.
There are at least two nodes in this BST.
您在真实的面试中是否遇到过这个题?
是
样例
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).
二叉搜索树BST的特点是左子树的值小于根节点,右子树的值大于根节点,所以进行中序遍历,得出每个根节点-左子树 和 右子树-根节点 的值 取其中的最小值即可。
/**
* 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 absolute difference between values of any two nodes
*/
int getMinimumDifference(TreeNode * root) {
// Write your code here
int res=INT_MAX;
int pre=-1;
inorder(root,pre,res);
return res;
}
void inorder(TreeNode * root,int &pre,int &res){
if(!root) return;
inorder(root->left,pre,res);
if(pre!=-1) res=min(res,root->val-pre);
pre=root->val;
inorder(root->right,pre,res);
}
};