class Solution {
public:
int result = INT_MAX;
TreeNode* pre = nullptr;
//采用中序遍历
void traversal(TreeNode* root) {
if (root == nullptr) return;
traversal(root->left);
if (pre != nullptr) result = min(result, root->val - pre->val);
pre = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
//常规方法
class Solution {
private:
//由于是二叉搜索树, 直接中序遍历
void searchBST(TreeNode* cur, unordered_map<int, int>& map) {
if (cur == nullptr) return;
//左
searchBST(cur->left, map);
//中
map[cur->val]++;
//右
searchBST(cur->right, map);
}
//从小到大排序
bool static cmp(const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
}
public:
vector<int> findMode(TreeNode* root) {
// <节点数,频次>
unordered_map<int, int> map;
vector<int> result;
if (root == NULL) return result;
searchBST(root, map);
vector<pair<int, int>> vec(map.begin(), map.end());
sort(vec.begin(), vec.end(), cmp);
// 倒排
result.push_back(vec[0].first);
for (int i = 1; i < vec.size(); i++) {
if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
else break;
}
return result;
}
};
由于是二叉搜索树
class Solution {
private:
//存放结果集
vector<int> result;
//遍历遍历过程中出现的最高频次
int maxCount = 0;
//该元素的出现频次
int count = 0;
//由于是二叉搜索树, 直接中序遍历
TreeNode* pre = nullptr;
void searchBST(TreeNode* cur) {
if (cur == nullptr) return;
//左
searchBST(cur->left);
//中
//第一个节点
if (pre == nullptr) {
count = 1;
//上个节点与当前节点val相同
}else if (pre->val == cur->val){
count++;
//上一个节点与当前节点的val不同
}else {
count = 1;
}
pre = cur;
//处理count 与 maxCount
if (count == maxCount) {
result.push_back(cur->val);
}else if (count > maxCount) {
maxCount = count;
result.clear();
result.push_back(cur->val);
}
//右
searchBST(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
searchBST(root);
return result;
}
};
class Solution {
public:
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 root;
else if (left != nullptr && right == nullptr) return left;
else if (left == nullptr && right != nullptr) return right;
//没有找到
return nullptr;
}
};