链接
https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
耗时
解题:7 min
题解:4 min
题意
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
思路
二叉树一次 dfs 遍历出所有节点值,存入数组中,将得到的数组排序,那么最小的差值一定在数组的相邻两数中产生,遍历一次数组找相邻两数的差值最小值即可。
时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)
AC代码
/**
* 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 {
private:
vector<int> nums;
public:
void dfs(TreeNode* root) {
if(root == NULL) return ;
nums.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
int getMinimumDifference(TreeNode* root) {
dfs(root);
sort(nums.begin(), nums.end());
int res = nums[1] - nums[0];
int n = nums.size();
for(int i = 2; i < n; ++i) {
res = min(res, nums[i]-nums[i-1]);
}
return res;
}
};