文章目录
Leetcode 530-二叉搜索树的最小绝对差
题目描述
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
解题思路
采用双指针的方法指向当前节点和前一个节点,从而计算相邻元素的差值,并与当前的最小值进行比较。
class Solution {
public:
int minResult = INT_MAX;
TreeNode* pre = nullptr;
void traversal(TreeNode* root) {
if (root == nullptr)return;
traversal(root->left);
if (pre != nullptr) minResult = min(minResult, root->val - pre->val);
pre = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return minResult;
}
};
Leetcode 501-二叉搜索树中的众数
题目描述
https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
解题思路
二叉搜索树(BST)的重新定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
返回的是众数的集合,因为可能有多个数出现的频率相同
class Solution {
public:
int maxTime = 0;
vector<int>result;
TreeNode* pre = nullptr;
unordered_map<int,int>map;
void traversal(TreeNode* root) {
if (root == nullptr)return;
traversal(root->left);
map[root->val]++;
if (pre == nullptr)map[root->val] = 1;
else if (pre->val == root->val)map[root->val]++;
if (map[root->val] > maxTime) {
result.clear();
result.push_back(root->val);
maxTime = map[root->val];
}
else if (map[root->val] == maxTime)result.push_back(root->val);
pre = root;
traversal(root->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return result;
}
};
Leetcode 236-二叉树的最近公共祖先
题目描述
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
解题思路
采用后序遍历,左右的处理逻辑是当遇到 p 或者 q 时向上返回,中节点则判断其左右子节点的返回值是否为空,如果均不为空,则为最近公共祖先。
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;
else return nullptr;
}
};