学习目标:
- 530.二叉搜索树的最小绝对差
- 501.二叉搜索树中的众数
- 236. 二叉树的最近公共祖先
学习内容:
530.二叉搜索树的最小绝对差
https://www.bilibili.com/video/BV1DD4y11779/?vd_source=aecfc9d884d326a8edbdf2f5958916a7
class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
if (cur == NULL) return;
traversal(cur->left); // 左
if (pre != NULL){ // 中
result = min(result, cur->val - pre->val);
}
pre = cur; // 记录前一个
traversal(cur->right); // 右
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
错误以及注意事项
- 第一个方法听懂了,中序遍历后作为数组做。二叉搜索树直观的想法就是使用中序遍历生成一个升序数组,在形成数组后,其他任务就好处理了。与此同时我们需要掌握双指针的方法。
- 第二个方法对于为什么pre=cur这里还是有点混沌?
501.二叉搜索树中的众数
// 如果不是二叉搜索树,只是普通的树的话,需要遍历
class Solution {
public:
void searchBST(TreeNode* cur,unordered_map<int,int>& map){
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;
}
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++) {
// 取最高的放到result数组中
if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
else break;
}
return result;
}
};
错误以及注意事项
- cmp函数:这是一个静态成员函数,用作 sort 函数的比较函数。它比较两个 pair<int, int> 类型的对象,根据它们的第二个元素(即节点值的出现次数)降序排序。
236. 二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return root;
if(root==p || root==q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left!=NULL && right!=NULL) return root;
else if(left==NULL && right!=NULL) return right;
else if(left!=NULL && right==NULL) return left;
else{
return NULL;
}
}
};
错误以及注意事项
- 左右中的后序遍历方式。
学习时间:
2023.12.21
2024.2.4 开始放寒假了,中间一个多月没有碰leetcode了,开始复建!争取回学校之前把一刷补完 sad