530二叉搜索树的最小差值
class Solution {
private:
vector<int> vec;
void travel(TreeNode* node, vector<int>& vec){
if(!node) return;
travel(node->left,vec);
vec.push_back(node->val);
travel(node->right,vec);
}
public:
int getMinimumDifference(TreeNode* root) {
vec.clear();
travel(root,vec);
int res = INT_MAX;
for(int i = 1; i < vec.size();i++){
if(res > vec[i] - vec[i-1]){
res = vec[i] - vec[i-1];
}
}
return res;
}
};
双指针法
class Solution {
private:
int res = INT_MAX;
TreeNode* pre = NULL;
void travel(TreeNode* node){
if(!node) return;
travel(node->left);
if(pre != NULL){
res = min(res,node->val - pre->val);
}
pre = node;
travel(node->right);
}
public:
int getMinimumDifference(TreeNode* root) {
travel(root);
return res;
}
};
501 二叉搜索树中的众数
bool cmp (pair<int, int>& a, pair<int, int>& b) {
return a.second > b.second;
}
class Solution {
private:
unordered_map<int,int> map;
void travel(TreeNode* node){
if(!node) return;
travel(node->left);
map[node->val]++;
travel(node->right);
}
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
if(!root) return res;
travel(root);
vector<pair<int, int>> vec(map.begin(), map.end());
sort(vec.begin(), vec.end(), cmp);
res.push_back(vec[0].first);
for (int i = 1; i < vec.size(); i++) {
if (vec[i].second == vec[0].second) res.push_back(vec[i].first);
else break;
}
return res;
}
};
class Solution {
private:
int maxCount = 0;
int count = 0;
TreeNode* pre = NULL;
vector<int> result;
void searchBST(TreeNode* cur) {
if (cur == NULL) return ;
searchBST(cur->left);
if (pre == NULL) {
count = 1;
} else if (pre->val == cur->val) {
count++;
} else {
count = 1;
}
pre = cur;
if (count == maxCount) {
result.push_back(cur->val);
}
if (count > maxCount) {
maxCount = count;
result.clear();
result.push_back(cur->val);
}
searchBST(cur->right);
return ;
}
public:
vector<int> findMode(TreeNode* root) {
count = 0;
maxCount = 0;
pre = NULL;
result.clear();
searchBST(root);
return result;
}
};
236 二叉树的最近公共先祖
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};