530.二叉搜索树的最小绝对差
文章链接:https://programmercarl.com/0530.二叉搜索树的最小绝对差.html
视频链接:https://www.bilibili.com/video/BV1DD4y11779/?vd_source=6cb513d59bf1f73f86d4225e9803d47b
题目链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
采用了上一题的方法:
class Solution {
public:
TreeNode* pre=NULL;
int getMinimumDifference(TreeNode* root) {
//利用搜索树的左中右的顺序
if(root==NULL) return INT_MAX;
//左
int left=getMinimumDifference(root->left);
//中
if(pre!=NULL) left=min(left,root->val-pre->val);
pre=root;
//右
int right=getMinimumDifference(root->right);
return min(left,right);
}
};
501.二叉搜索树中的众数
文章链接:https://programmercarl.com/0501.二叉搜索树中的众数.html
题目链接:https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
视频链接:https://www.bilibili.com/video/BV1fD4y117gp/?vd_source=6cb513d59bf1f73f86d4225e9803d47b
class Solution {
public:
int count=1;
int maxCount=1;
queue<int> que;
TreeNode* pre=NULL;
void traversal(TreeNode* root){
if(root==NULL) return;
//左
traversal(root->left);
//中
if(pre!=NULL&&root->val==pre->val) count++;
else count=1;
pre=root;
if(count>maxCount){
maxCount=count;
while(!que.empty()) que.pop();
que.push(pre->val);
}
else if(count==maxCount) que.push(pre->val);
//右
traversal(root->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
vector<int> res;
while(!que.empty()){
res.push_back(que.front());
que.pop();
}
return res;
}
};
236. 二叉树的最近公共祖先
文章链接:https://programmercarl.com/0236.二叉树的最近公共祖先.html
题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
总结:这个题稍有难度,以后多做几遍
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==q||root==p||root==NULL) return root;
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left!=NULL&&right!=NULL) return root;
if(left==NULL) return right;
return left;
}
};
标签:pre,TreeNode,随想录,二叉,搜索,return,NULL,root,left
From: https://www.cnblogs.com/VickyWu/p/18537662