代码随想录算法训练营第21天| 530.二叉搜索树的最小绝对差 、501.二叉搜索树中的众数 、236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
第一个想法是,中序遍历得到数组,然后再依次相减。
class Solution {
private:
vector<int> vec;
void traversal(TreeNode* root) {
if (root == nullptr) return ;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
vec.clear();
traversal(root);
if (vec.size() < 2) return 0;
int res = INT_MAX;
for (int i = 1; i < vec.size(); ++i) {
res = min(res, vec[i] - vec[i - 1]);
}
return res;
}
};
同样也可以使用两个指针来代替数组:
class Solution{
private:
TreeNode* pre = nullptr;
int res = INT_MAX;
void traversal(TreeNode* cur) {
if(cur == nullptr) return;
traversal(cur->left);
if(pre != nullptr) {
result = min((cur->val - pre->val), res);
}
pre = cur;
traversal(cur->right);
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return res;
}
};
501.二叉搜索树中的众数
同样可以利用对二叉搜索树中序遍历得到的序列是有序的这个特点,使用两个指针就可以完成。
class Solution {
private:
int maxCount = 0;
int count = 0;
TreeNode* pre = nullptr;
vector<int> res;
void searchBST(TreeNode* cur) {
if(cur == nullptr) return;
//左
searchBST(cur->left);
//中
if(pre == nullptr) count = 1; //说明是第一个节点
else if(pre->val == cur->val) { //与前一个节点数值相等
++count;
}
// 和前一个节点的值不同
else {
count = 1;
}
// 更新上一个节点
pre = cur;
if(count == maxCount) { //如果和最大值相同,则放进res
res.push_back(cur->val);
}
if(count > maxCount) { //如果出现计数大于了最大值
maxCount = count;
res.clear(); //清空数组,重新进入
res.push_back(cur->val);
}
searchBST(cur->right); //右
return;
}
public:
vector<int> findMode(TreeNode* root) {
count = 0;
maxCount = 0;
TreeNode* pre = nullptr;
res.clear();
searchBST(root);
return res;
}
};
236. 二叉树的最近公共祖先
二叉树的遍历是从上往下的,要达到从下往上的查找,可以使用回溯的方法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == q || root == q || root == nullptr)
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 left;
} else if (left == nullptr && right != nullptr) {
return right;
} else if (left == nullptr && right == nullptr) {
return nullptr;
}
}
};