530.二叉搜索树的最小绝对差
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
和验证二叉搜索树其实是一个逻辑,利用一个pre来记录前一位的二叉树节点,再用一个min变量来记录当前节点和前一个节点的差值,只要差值比min记录的更小,就更新min
class Solution {
public:
TreeNode* pre = nullptr;
int min = INT_MAX;
int getMinimumDifference(TreeNode* root) {
if(root->left) getMinimumDifference(root->left);
if(pre) min = min < root->val - pre->val ? min : root->val - pre->val;
pre = root;
if(root->right) getMinimumDifference(root->right);
return min;
}
};
501.二叉搜索树中的众数
https://leetcode.cn/problems/find-mode-in-binary-search-tree/
寻找众数和找最小绝对差是一个思路,需要用一个count变量来记录当前元素出现的次数,用一个maxcount来记录最大count,只要count比maxcount大了就更新maxcount并且更新result
class Solution {
public:
int maxCount = 0;
int count = 0;
TreeNode* pre = nullptr;
vector<int> result = {};
void traversal(TreeNode* cur){
if(!cur) return;
traversal(cur->left);
if(!pre) count = 1;
else if(pre->val == cur->val) count++;
else count = 1;
pre = cur;
if(count == maxCount) result.push_back(cur->val);
if(count > maxCount){
result.clear();
result.push_back(cur->val);
maxCount = count;
}
traversal(cur->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return result;
}
};
236. 二叉树的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
本题采用后序遍历,左、右、中的顺序更容易发现公共祖先
如果遍历到最后还没有找到目标节点就返回空节点
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || 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;
if(left && !right) return left;
if(!left && right) return right;
return nullptr;
}
};