530.二叉搜索树的最小绝对差
题目链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<int> vec;// 将二叉搜索树转换为有序数组
void travesal(TreeNode* root){
if(root==nullptr) return;
travesal(root->left);
vec.push_back(root->val);
travesal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
vec.clear();
travesal(root);
if(vec.size()<2)
return 0;
int result = INT_MAX;
for (int i = 1; i<vec.size();i++){
//统计有序数组的最小差值
result = min(result, vec[i] - vec[i-1]);
}
return result;
}
};
501.二叉搜索树中的众数
题目链接:https://leetcode.cn/problems/find-mode-in-binary-search-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private://统计树中元素出现的频率
void searchBST(TreeNode* cur, unordered_map<int,int>& map){
//key元素 value频率
if(cur==nullptr) return;
map[cur->val]++;
searchBST(cur->left,map);
searchBST(cur->right,map);
return ;
}
bool static cmp (const pair<int,int>&a, const pair<int,int>&b){
//给统计出来的出现频率排个序
return a.second > b.second; //按照从大到小排序
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int,int> map;
vector<int> result;
if(root == nullptr) return result;
searchBST(root,map);
vector<pair<int,int>> vec(map.begin(), map.end());
sort(vec.begin(),vec.end(),cmp); //对频率排序
result.push_back(vec[0].first);
//如果有相等的频率则一并输出
for(int i = 1;i < vec.size(); i++){
if(vec[i].second == vec[0].second)
result.push_back(vec[i].first);
else break;
}
return result;
}
};
236. 二叉树的最近公共祖先
题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/submissions/
本题的回溯遍历有点绕,需要多理解。
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q || root == NULL)
return root;
//搜索整棵树
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(left != NULL && right!= NULL) //回溯遍历二叉树,将结果返回头结点
return root;
if(left == NULL && right!= NULL)
return right;
else if(left != NULL && right == NULL)
return left;
else
return NULL;
}
};