530.二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
文章讲解:代码随想录
class Solution {
public:
void tra(TreeNode* root,vector<int>&nums){
if (root==nullptr){return ;}
tra(root->left,nums);
nums.push_back(root->val);
tra(root->right,nums);
}
int getMinimumDifference(TreeNode* root) {
vector<int>nums;
tra(root,nums);
vector<int>ans;
for(int i=1;i<nums.size();i++){
ans.push_back(abs(nums[i]-nums[i-1]));
}
int result=INT_MAX;
for(auto x:ans){
if(x<result){result=x;}
}
return result;
}
};
501.二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
文章讲解:代码随想录
第一次解答:
class Solution {
public:
TreeNode*pre=nullptr;
int count=1;
int maxCount=0;
vector<int>ans;
void tra(TreeNode*root){
if(root==nullptr){return;}
tra(root->left);
if(root->val!=pre->val){
pre =root;
count=1;
}
else{
count++;
}
if(count>maxCount){
maxCount=count;
ans.push_back(pre->val);
}
}
vector<int> findMode(TreeNode* root) {
if(root!=nullptr){pre=root;}
tra(root);
return ans;
}
};
问题:1.ans数组的更新逻辑
ans
应该存储所有出现次数等于maxCount
的值,而不是只要count > maxCount
就加入。如果后续有新的count > maxCount
,应该清空ans
并重新加入新的值。
2.pre数组的初始化问题
正确解答:
class Solution {
public:
TreeNode*pre=nullptr;
int count=1;
int maxCount=0;
vector<int>ans;
void tra(TreeNode*root){
if(root==nullptr){return;}
tra(root->left);
if(pre==nullptr||root->val!=pre->val){
count=1;
}
else{
count++;
}
if(count>maxCount){
maxCount=count;
ans.clear();
ans.push_back(root->val);
}else if(count==maxCount){
ans.push_back(root->val);
}
pre=root;
tra(root->right);
}
vector<int> findMode(TreeNode* root) {
tra(root);
return ans;
}
};
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
文章讲解:代码随想录
思路:
这道题要用后序遍历
处理好单层判断逻辑
如果左空 右不空 应该把右返回给上一层
如果右空,左不空,应该把左返回给上一层
都不为空的话 就返回当前节点
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//确定终止条件
if(root==nullptr){
return nullptr;
}
if(root==p||root==q){
return root;
}
//后序遍历
auto left=lowestCommonAncestor(root->left,p,q);
auto right=lowestCommonAncestor(root->right,p,q);
if(left!=nullptr&&right!=nullptr){return root;}
if(left==nullptr&&right!=nullptr){return right;}
if(left!=nullptr&&right==nullptr){return left;}
return nullptr;
}
};