Title
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
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).
Note: There are at least two nodes in this BST.
注意是二叉排序树,因此中序遍历就是一个有序数组了,可以在中序遍历中改造
Solution
//cpp:
/**
* 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:
int minn=INT_MAX,val=-1;
int getMinimumDifference(TreeNode* root) {
if(root->left) getMinimumDifference(root->left);
if(val>=0) minn=min(minn,abs(root->val-val));
val=root->val;
if(root->right) getMinimumDifference(root->right);
return minn;
}
};