530 二叉搜索树的最小绝对差
class Solution
{
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur)
{
if (cur == NULL) return;
traversal(cur->left); // 左
if (pre != NULL){ // 中
result = min(result, cur->val - pre->val);
}
pre = cur; // 记录前一个
traversal(cur->right); // 右
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
501二叉搜索树中的众数
class Solution {
public:
TreeNode*pre=NULL;
int c=0;
int maxc=0;
vector<int>res;
vector<int> findMode(TreeNode* root)
{
dg(root);
return res;
}
void dg(TreeNode* root)
{
if(root==NULL) return;
dg(root->left);
if(pre==NULL)
{
c=1;
}
else if(pre->val==root->val)
{
c++;
}
else c=1;
pre=root;
if(c==maxc)
{
res.push_back(root->val);
}
if(c>maxc)
{
maxc=c;
res.clear();
res.push_back(root->val);
}
dg(root->right);
return;
}
};
236 二叉树最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(root==nullptr) return nullptr;
if(root->val==p->val||root->val==q->val)
{
return root;
}
TreeNode*l=lowestCommonAncestor(root->left,p,q);
TreeNode*r=lowestCommonAncestor(root->right,p,q);
if(l&&r)
{
return root;
}
return r!=nullptr?r:l;
}
};