代码随想录算法训练营第二十一天| 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
题目链接
文章讲解
class Solution {
public:
void traversal(TreeNode* cur, int& pre, int& minimumDiff) {
if (!cur) return;
traversal(cur->left, pre, minimumDiff);
if (pre != -1 && cur->val - pre < minimumDiff)
minimumDiff = cur->val - pre;
pre = cur->val;
traversal(cur->right, pre, minimumDiff);
}
int getMinimumDifference(TreeNode* root) {
int minimumDiff = INT32_MAX, pre = -1;
traversal(root, pre, minimumDiff);
return minimumDiff;
}
};
501.二叉搜索树中的众数
题目链接
文章讲解
class Solution {
public:
void traversal(TreeNode* cur, int& pre, int& count, int& max, vector<int>& ans) {
if (!cur) return;
traversal(cur->left, pre, count, max, ans);
if (pre == INT32_MIN) {
count = 1;
} else {
if (pre == cur->val) {
count++;
} else {
count = 1;
}
}
if (count > max) {
max = count;
ans.clear();
ans.push_back(cur->val);
} else if (count == max) {
ans.push_back(cur->val);
}
pre = cur->val;
traversal(cur->right, pre, count, max, ans);
}
vector<int> findMode(TreeNode* root) {
vector<int> ans;
int pre = INT32_MIN, count = 0, max = 0;
traversal(root, pre, count, max, ans);
return ans;
}
};
236. 二叉树的最近公共祖先
题目链接
文章讲解
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == p || root == q || root == NULL) return root;
TreeNode* leftTree = lowestCommonAncestor(root->left, p, q);
TreeNode* rightTree = lowestCommonAncestor(root->right, p, q);
if (leftTree && rightTree)
return root;
if (leftTree)
return leftTree;
if (rightTree)
return rightTree;
return NULL;
}
};