文档讲解:代码随想录 (programmercarl.com)
视频讲解:代码随想录的个人空间-代码随想录个人主页-哔哩哔哩视频 (bilibili.com)
LeetCode 二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
解题思路:中序遍历为递增序列,利用二叉搜索树这一特性保存每次比较的最小差值即可。
class Solution {
public:
TreeNode* pre=nullptr;
int res=INT_MAX;
void travsal(TreeNode* root){
if(!root)return;
travsal(root->left);
if(pre)res=min(res,root->val-pre->val);
pre=root;
travsal(root->right);
}
int getMinimumDifference(TreeNode* root) {
travsal(root);
return res;
}
};
LeetCode 二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
解题思路:还是中序遍历,随时更新最大值并保存到数组中。
解题代码如下(下面代码来自代码随想录 (programmercarl.com)):
class Solution {
public:
int count=0;
int maxcount=0;
vector<int>res;
TreeNode*pre=nullptr;
void travsal(TreeNode* root){
if(!root)return;
travsal(root->left);
if(pre&&pre->val==root->val)count++;
else count=1;
pre=root;
if(count==maxcount)res.push_back(root->val);
if(count>maxcount){
res.clear();
res.push_back(root->val);
maxcount=count;
}
travsal(root->right);
}
vector<int> findMode(TreeNode* root) {
travsal(root);
return res;
}
};
LeetCode 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
解题思路:后根遍历。
解题代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==p||root==q||!root)return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left&&right)return root;
if(!left)return right;
return left;
}
};