题目:
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.
题目链接
题意:
给了一棵二叉搜索树,让你找树上任意两个节点的最小绝对值。
想了半天二叉搜索树的性质,也没用上,无奈写出了二叉树通用解法,,居然没有TLE,,,果然是easy难度的题目啊。。。
普通二叉树的写法是把所有数提取出来排序,之后在找相邻的两个数中的最小差值。
代码如下:
class Solution {
public:
vector<int> dic;
void dfs(TreeNode* node) {
dic.push_back(node->val);
if (node->left != NULL) {
dfs(node->left);
}
if (node->right != NULL) {
dfs(node->right);
}
}
int getMinimumDifference(TreeNode* root) {
dfs(root);
sort(dic.begin(), dic.end());
int Min = 0x3f3f3f3f;
for (int i = 1; i < dic.size(); i ++) {
Min = min(Min, dic[i] - dic[i-1]);
}
return Min;
}
};