- 530.二叉搜索树的最小绝对差
- 501.二叉搜索树中的众数
- 236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差 和昨天那道差不多,主要利用二叉搜索树的性质
vector<int> v1;
int result = INT_MAX;
TreeNode* pre = nullptr;
void makeve(TreeNode* root) {
if (root == nullptr)
return;
makeve(root->left);
if (pre != nullptr) {
result = min(result, root->val - pre->val);
}
pre = root;
makeve(root->right);
return;
}
int getMinimumDifference(TreeNode* root) {
makeve(root);
return result;
}
501.二叉搜索树中的众数 这思路针不戳
int maxconut = 0;
int count = 0;
vector<int> end;
TreeNode* pre = nullptr;
void getcont(TreeNode* root) {
if (root == nullptr)
return;
getcont(root->left);
if (pre == nullptr) { // 说明刚进来第一次
count = 1;
} else if (pre->val == root->val) {
count++;
} else {
count = 1;
}
if (maxconut == count) {
end.push_back(root->val);
}
if (maxconut < count) {
end.clear();
maxconut = count;
end.push_back(root->val);
}
pre = root;
getcont(root->right);
return;
}
vector<int> findMode(TreeNode* root) {
getcont(root);
return end;
}
236. 二叉树的最近公共祖先
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//终止条件:
if(root==nullptr) return nullptr;
if(root==p||root==q)return root;
//遍历顺序:
TreeNode* left=lowestCommonAncestor(root->left,p,q);
TreeNode* right=lowestCommonAncestor(root->right,p,q);
if(left!=nullptr&&right!=nullptr)return root;
else if(left==nullptr&&right!=nullptr)return right;
else if(left!=nullptr&&right==nullptr)return left;
else{
return nullptr;
}
}