530. 二叉搜索树的最小绝对差
思路
按照中序遍历来做,每次要记录前一个结点的值,引入pre
来记忆
代码
class Solution {
public:
int res = INT_MAX;
TreeNode* pre = nullptr;
int getMinimumDifference(TreeNode* root) {
if (!root) return 0;
getMinimumDifference(root->left);
if (pre != nullptr) res = min(res, abs(root->val - pre->val));
pre = root;
getMinimumDifference(root->right);
return res;
}
};
- 迭代
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
if (!root) return 0;
stack<TreeNode*> stk;
TreeNode* cur = root;
int res = INT_MAX;
TreeNode* pre = nullptr;
while (cur != nullptr || !stk.empty()){
if (cur != nullptr){
stk.push(cur);
cur = cur->left;
}else{
cur = stk.top();
stk.pop();
if (pre != nullptr) res = min(res, abs(cur->val - pre->val));
pre = cur;
cur = cur->right;
}
}
return res;
}
};
501. 二叉搜索树中的众数
思路
- 二叉树全部遍历一遍,然后排序,按照出现最大次数的找到
- 二叉搜索树性质,左<中<右,按照顺序遍历,两个相同的一定是挨着出现的,只不过要注意找到最大众数每次要清理之前放入的数值
代码
- 二叉树通用代码
class Solution {
public:
unordered_map<int, int> map;
vector<int> findMode(TreeNode* root) {
traversal(root);
int a = 0;
vector<int> res;
for (auto it = map.begin(); it != map.end(); it++){
if (it->second >= a) a = it->second;
}
for (auto it = map.begin(); it != map.end(); it++){
if (it->second == a) res.push_back(it->first);
}
return res;
}
void traversal(TreeNode* root){
if (!root) return;
traversal(root->left);
map[root->val] ++;
traversal(root->right);
return;;
}
};
- 二叉搜索树代码
class Solution {
public:
vector<int> res;
int max = 0;
int maxcount = 0;
int count = 0;
TreeNode* pre = nullptr;
vector<int> findMode(TreeNode* root) {
traversal(root);
return res;
}
void traversal(TreeNode* root){
if (!root) return;
traversal(root->left);
if (pre == nullptr){
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);
}
traversal(root->right);
return;
}
};
👀236. 二叉树的最近公共祖先
思路
- 回溯过程是自底向上,所有只能选择后序遍历,而且是要遍历整棵树,所以是递归过程不进行条件判断
- 假如说找到
p
或q
的祖先,那么需要回溯网上传递,因此需要对left
和right
进行判断
代码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == p || root == q || root == nullptr) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (!left && right) return right;
if (!right && left) return left;
return nullptr;
}
};