530. 二叉搜索树的最小绝对差
就中序遍历算了,简洁易懂
class Solution {
public:
vector<int> nums;
// 比较的时候只用比较连着的
int getMinimumDifference(TreeNode* root) {
dfs(root);
int minn = nums[1] - nums[0];
for (int i = 1; i < nums.size(); i ++)
{
minn = min(minn, nums[i] - nums[i-1]);
}
return minn;
}
void dfs(TreeNode* root)
{
if (root == nullptr) return;
dfs(root->left);
nums.push_back(root->val);
dfs(root->right);
}
};
501. 二叉搜索树中的众数
中序遍历,哈希计数后排下序
class Solution {
public:
vector<int> nums;
vector<int> findMode(TreeNode* root) {
dfs(root);
unordered_map<int, int> umap;
for (auto i : nums) umap[i] ++;
vector<pair<int, int>> vec;
for (auto [x, y] : umap)
{
vec.push_back({y, x});
}
sort(vec.begin(), vec.end(), [](pair<int, int>&x, pair<int, int>&y)
{
return x.first > y.first;
});
vector<int> res;
res.push_back(vec[0].second);
int target = vec[0].first;
for (int i = 1; i < vec.size(); i ++)
{
if (vec[i].first != target) break;
res.push_back(vec[i].second);
}
return res;
}
void dfs(TreeNode* root)
{
if (root == nullptr) return;
dfs(root->left);
nums.push_back(root->val);
dfs(root->right);
}
};
236. 二叉树的最近公共祖先
先确定终止条件,为空或者找到了目标节点,返回该节点。
分三种情况:
- 左右都为空,返回空
- 有一边不为空,返回这一边
- 两边都不为空,返回root
class Solution {
public:
// 都为空->空 都不为空->root 一边不为空->非空一边
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 nullptr;
if (left == nullptr) return right;
if (right == nullptr) return left;
return root;
}
};