530. Minimum Absolute Difference in BST
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.
求二叉搜索树中,任意两个节点的值之间的最小绝对差值
C++(19ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int getMinimumDifference(TreeNode* root) { 13 int minValue = INT_MAX ; 14 int val = -1 ; 15 inorder(root,minValue,val) ; 16 return minValue ; 17 } 18 19 void inorder(TreeNode* root , int& minValue , int& val){ 20 if (root->left != NULL) 21 inorder(root->left,minValue,val) ; 22 if (val >= 0) 23 minValue = min(minValue , root->val - val) ; 24 val = root->val ; 25 if (root->right != NULL) 26 inorder(root->right,minValue,val) ; 27 } 28 };