530.二叉搜索树的最小绝对差
C++:
class Solution {
public:
vector<int> vec;
void traversal(TreeNode* root) {
if (root == NULL) return;
traversal(root->left);
vec.push_back(root->val); // 将二叉搜索树转换为有序数组
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
vec.clear(); // 不加这句在leetcode上也可以过,但最好加上
traversal(root);
int res=INT_MAX;
for (int i = 1; i < vec.size(); i++) {
// 注意要小于等于,搜索树里不能有相同元素
if (vec[i]-vec[i - 1]<=res) res=vec[i]-vec[i - 1];
}
return res;
}
};
501.二叉搜索树中的众数
C++:迭代器
class Solution {
public:
int maxIndex=0;
/*vector<vector<int>> map;*/
void accessTree(TreeNode*root,unordered_map<int, int>& map)
{
if(root==NULL) return;
map[root->val]++;
if(map[root->val]>maxIndex) maxIndex=map[root->val];
accessTree(root->left,map);
accessTree(root->right,map);
return;
}
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> map; // key:元素,value:出现频率
vector<int> res;
if(root==NULL) return res;
accessTree(root,map);
for(auto it=map.begin();it!=map.end();it++){
if(it->second==maxIndex)
res.push_back(it->first);
}
return res;
}
};
C++:pair
class Solution {
public:
//int maxIndex=0;
/*vector<vector<int>> map;*/
void accessTree(TreeNode*root,unordered_map<int, int>& map)
{
if(root==NULL) return;
map[root->val]++;
//if(map[root->val]>maxIndex) maxIndex=map[root->val];
accessTree(root->left,map);
accessTree(root->right,map);
return;
}
bool static cmp(pair<int,int>&a,pair<int,int>&b){
return a.second>b.second;
}
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> map; // key:元素,value:出现频率
vector<int> res;
if(root==NULL) return res;
accessTree(root,map);
vector<pair<int,int>> vec(map.begin(),map.end());//存储
sort(vec.begin(),vec.end(),cmp);//降序
for(int i=0;i<vec.size();i++){
if(vec[i].second==vec[0].second)
res.push_back(vec[i].first);
}
return res;
}
};
236. 二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
if(root==p||root==q) return root;
TreeNode*left=lowestCommonAncestor(root->left,p,q);//左
TreeNode*right=lowestCommonAncestor(root->right,p,q);//右
if(left!=nullptr&&right!=nullptr) return root;//中
else if(left!=nullptr&&right==nullptr) return left;
else if(left==nullptr&&right!=nullptr) return right;
else return nullptr;
}
};