代码随想录算法训练营第十八天| 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先

发布时间 2023-06-27 11:25:16作者: 博二爷

530.二叉搜索树的最小绝对差

思路:

根据二叉搜素树的特点,直接中序遍历,就是有序数组,然后两个节点进行比较,就可以

代码:

 1 int getMinimumDifference(TreeNode* root) {
 2     if(!root) return 0;
 3     int result = INT_MAX;
 4     multiset<int> vals;
 5     stack<TreeNode*> selected;
 6     selected.push(root);
 7     while (!selected.empty())
 8     {
 9         auto cur_ = selected.top(); selected.pop();
10         vals.insert(cur_->val);
11 
12         if (cur_->left) selected.push(cur_->left);
13         if (cur_->right) selected.push(cur_->right);
14     }
15 
16     for (auto i = vals.begin(); i != --vals.end(); i++)
17     {
18         auto j = next(i);
19         if (abs(*i - *j) < result) {
20             result = abs(*i - *j);
21         }
22     }
23 
24     return result;
25 }