代码随想录算法训练营第二十三天
530.二叉搜索树的最小绝对差
题目链接:530.二叉搜索树的最小绝对差
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode*pre = nullptr;
int min_d = INT_MAX;
int getMinimumDifference(TreeNode* root) {
if(!root)return 0;
int left_b = getMinimumDifference(root->left);
if(pre){
min_d = min(min_d,root->val-pre->val);
};
pre =root;
int right_b = getMinimumDifference(root->right);
return min_d;
}
};
501.二叉搜索树中的众数
题目链接:501.二叉搜索树中的众数
相邻两个节点相等计数器加1,计数大于最大值就更新最大值,然后把之前收集的结果清空,证明之前收集的结果是错的,计数等于最大值就把该节点的值加入结果集
class Solution {
public:
int countMax = INT_MIN;
int count = 0;
TreeNode* pre = nullptr;
void find(TreeNode* root, vector<int>& result) {
if (root == nullptr)
return;
find(root->left, result);
if (pre && pre->val == root->val) {
count++;
} else { // pre ==null&&相邻节点不等,计数器都要重置
count = 1;
}
if (count > countMax) {
countMax = count;
result.clear(); //清空现有结果集,加入新的结果
result.push_back(root->val);
} else if (count == countMax) {
result.push_back(root->val);
}
pre = root;
find(root->right, result);
}
vector<int> findMode(TreeNode* root) {
vector<int> result;
find(root, result);
return result;
}
};
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root)return nullptr;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(root == p||root ==q)return root;
if(left!=nullptr&&right==nullptr)return left;
else if (left ==nullptr&&right!=nullptr)return right;
else if(left!=nullptr&&right !=nullptr)return root;
else return nullptr;
}
};