中序遍历,双指针
class Solution {
public:
TreeNode* pre = nullptr;
int result = INT_MAX;
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
void traversal(TreeNode* root) {
if (!root) {
return;
}
traversal(root->left);
if (pre) {
result = min(result, root->val - pre->val);
}
pre = root;
traversal(root->right);
}
};
中序遍历存放进数组
class Solution {
public:
vector<int> path;
int getMinimumDifference(TreeNode* root) {
int result = INT_MAX;
inorderTra(root);
for (int i = 1; i < path.size(); i++) {
result = min(result, path[i] - path[i - 1]);
}
return result;
}
void inorderTra(TreeNode* root) {
if (!root) {
return;
}
inorderTra(root->left);
path.push_back(root->val);
inorderTra(root->right);
}
};
常规做法
class Solution {
public:
unordered_map<int, int> map;
bool static cmp(const pair<int, int>& l, const pair<int, int>& r) {
return l.second > r.second;
}
vector<int> findMode(TreeNode* root) {
vector<int> res;
inorderTra(root);
vector<pair<int, int>> path(map.begin(), map.end());
sort(path.begin(), path.end(), cmp);
res.push_back(path[0].first);
for(int i = 1; i < path.size(); i++) {
if (path[i].second == path[0].second){
res.push_back(path[i].first);
}else {
break;
}
}
return res;
}
void inorderTra(TreeNode* root) {
if (!root) {
return ;
}
inorderTra(root->left);
map[root->val]++;
inorderTra(root->right);
}
};
二叉搜索树中
class Solution {
public:
int count = 0;
int maxCount = 0;
TreeNode* pre = nullptr;
vector<int> res;
void searchBST(TreeNode* root) {
if (!root){
return;
}
searchBST(root->left);
if (!pre) {
count = 1;
}else if (pre->val == root->val){
count++;
}else {
count = 1;
}
pre = root;
if (count == maxCount) {
res.push_back(root->val);
}
if (count > maxCount) {
maxCount = count;
res.clear();
res.push_back(root->val);
}
searchBST(root->right);
}
vector<int> findMode(TreeNode* root) {
searchBST(root);
return res;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p , q);
if (left && right) {
return root;
} else if (!left) {
return right;
}
return left;
}
};