代码随想录第二十一天|Leetcode530.二叉搜索树的最小绝对差、Leetcode501.二叉搜索树中的众数、Leetcode236. 二叉树的最近公共祖先
Leetcode530.二叉搜索树的最小绝对差
比较简单,有序树直接中序遍历就是有序数组,就能直接拿来用了
class Solution {
private:
vector<int> vec;
void dfs(TreeNode* root){
if(root==NULL) return;
dfs(root->left);
vec.push_back(root->val);
dfs(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
dfs(root);
int result=INT_MAX;
for(int i=0;i<vec.size()-1;i++){
result=min(result,abs(vec[i]-vec[i+1]));
}
return result;
}
};
Leetcode501.二叉搜索树中的众数
用unordered_map自己写了一个,时间上是2n,相对差一些
class Solution {
private:
unordered_map<int,int> uMap;
void traversal(TreeNode* root){
if(root==NULL) return;
traversal(root->left);
uMap[root->val]++;
traversal(root->right);
}
public:
vector<int> findMode(TreeNode* root) {
traversal(root);
vector<int> result;
int count=0;
for(unordered_map<int,int>::iterator i=uMap.begin();i!=uMap.end();i++){
count=max(count,i->second);
}
for(unordered_map<int,int>::iterator i=uMap.begin();i!=uMap.end();i++){
if(i->second==count) result.push_back(i->first);
}
return result;
}
};
把二叉搜索树的有序性利用上,对其进行中序遍历
class Solution {
private:
vector<int> result;
int maxCount,count,base;
void update(int val){
if(val==base) count++;
else {
count=1;
base=val;
}
if(count==maxCount){
result.push_back(base);
}
if(count>maxCount){
maxCount=count;
result=vector<int> {base};
}
}
void dfs(TreeNode* root){
if(root==NULL) return;
dfs(root->left);
update(root->val);
dfs(root->right);
}
public:
vector<int> findMode(TreeNode* root) {
dfs(root);
return result;
}
};
Leetcode236. 二叉树的最近公共祖先
返回值的设置很巧妙,如果找到了就一路返回,找不到就返回NULL。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
if(root==q||root==p) 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&&right!=NULL) return right;
return left;
}
};