二叉搜索树的最小绝对差
和验证二叉搜索树的思路一样,用双指针。
TreeNode* pre;
然后再设个int min=INT_MAX;
当(root->val-pre->val)<min时更新min
用中序遍历
二叉搜索树中的众数
如果给一个数组,要找出现频率最高的数,会很自然的想到用map来统计。
class Solution {
public:
map<int,int> mp;
void get(TreeNode* root){
if(root==NULL) return;
mp[root->val]++;
get(root->left);
get(root->right);
}
class compare{
public:
bool operator()(pair<int,int>p1,pair<int,int>p2){
return p1.second<p2.second;//大顶堆
}
};
vector<int> findMode(TreeNode* root) {
vector<int> result;
get(root);
priority_queue< pair<int,int>,vector<pair<int,int>>,compare> a;//创建一个大顶堆
for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
a.push(*it);
}
int max=a.top().second;
while (!a.empty()&&a.top().second == max) { //用栈,队列,堆前一定要检查是否为空,否则会超出内存限制
result.push_back(a.top().first);
a.pop();
}
return result;
}
};
而这里是二叉搜索树,其特点是中序遍历可以得到一个有序数组,面对有序数组时,会想到可以用双指针来解决问题。
int max=0;//统计出现最高出现频率
int pin=0;//统计当前频率
TreeNode* pre=NULL;
void find(TreeNode* cur){
if(cur==NULL) return;//终止条件
find(cur->left);
if(pre!=NULL&&pre->val==cur->val){
pin++;//频率加1
}
else{
pin=1;
pre=cur;//不等时更新pre
}
if(pin>max){
result.clear();//将前面统计过的都清理掉
result.push_back(cur->val);
max=pin;
}
else if(pin==max){
result.push_back(cur->val);
}
find(cur->right);
}
二叉树的最近公共祖先
题目
找最靠近的公共点,应该是从下往上寻找,用后序。
后序是天然的回溯过程。
如果root的左子树中有p,则返回p,右子树中有q则返回q;
什么都没有就返回NULL;
如果以一个点的左右子树都不为空,说明他就是最近公共祖先。
假如它作为上一个目标节点的left,则要想办法把它传回去,由此判断left有right空时目标节点要返回left;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
else if(root==p||root==q) return root;
//后序遍历
TreeNode* left=lowestCommonAncestor(root->left,p,q);//用left来接住结果
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left==NULL&&right==NULL) return NULL;
else if(left!=NULL&&right!=NULL) return root;
else if(left!=NULL&&right==NULL) return left;//一遍空一遍有,返回有的那边
//注意不是返回root->right
else return right;
}