代码随想录算法训练营第37期 第二十一天 | LeetCode530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先
一、530.二叉搜索树的最小绝对差
解题代码C++:
cpp
/**
* 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 {
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;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0530.二叉搜索树的最小绝对差.html
二、501.二叉搜索树中的众数
解题代码C++:
cpp
/**
* 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 {
private:
int maxCount = 0;
int count = 0;
TreeNode* pre = NULL;
vector<int> result;
void searchBST(TreeNode* cur)
{
if(cur == NULL) return;
searchBST(cur->left);
if(pre == NULL)
count = 1;
else if(pre->val == cur->val)
count ++;
else
count = 1;
pre = cur;
if(count == maxCount)
result.push_back(cur->val);
if(count > maxCount)
{
maxCount = count;
result.clear();
result.push_back(cur->val);
}
searchBST(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
count = 0;
maxCount = 0;
pre = NULL;
result.clear();
searchBST(root);
return result;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0501.二叉搜索树中的众数.html
三、236. 二叉树的最近公共祖先
解题代码C++:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == q || root == p || root == NULL) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left != NULL && right != NULL) return root;
if(left == NULL) return right;
return left;
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0236.二叉树的最近公共祖先.html