530.二叉搜索树的最小绝对差
530.二叉搜索树的最小绝对差
迭代
中序遍历得到的结果是有序的,最小的绝对差只可能出现在相邻元素中;
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
TreeNode* pre = nullptr;
stack<TreeNode*> stk;
int minDiff = INT_MAX;
while(!stk.empty() || root != nullptr) {
if(root != nullptr) {
stk.push(root);
root = root->left;
}
else {
root = stk.top();
stk.pop();
if (pre != nullptr) {
minDiff = min(minDiff, root->val - pre->val);
}
pre = root;
root = root->right;
}
}
return minDiff;
}
};
递归
class Solution {
int diff = INT_MAX;
TreeNode* pre = nullptr;
public:
void traversal(TreeNode* cur) {
if (cur == nullptr) {
return;
}
traversal(cur->left); // 左
if (pre != nullptr){ // 中
diff = min(diff, cur->val - pre->val);
}
pre = cur; // 记录前一个
traversal(cur->right); // 右
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return diff;
}
};
501.二叉搜索树中的众数
遍历二叉树,使用map存储相同节点值和个数;在遍历map,取出可以作为众数的节点值;
class Solution {
unordered_map<int, int> m;
public:
void traversal(TreeNode* root) {
if (root == nullptr) {
return;
}
traversal(root->left);
++m[root->val];
traversal(root->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
int count = INT_MIN;
vector<int> res;
for (auto [val, cnt] : m) {
if (cnt > count) {
res.clear();
count = cnt;
res.push_back(val);
} else if (cnt == count) {
res.push_back(val);
}
}
return res;
}
};
利用二叉搜索树 有序的特性
class Solution {
int maxCnt = 0; // 存储最大频率
int count = 0; // 存储当前元素值的频率
vector<int> res;
TreeNode* pre = nullptr; // 前一个节点值
public:
void searchBST(TreeNode* cur) {
if (cur == nullptr) {
return ;
}
searchBST(cur->left); // 左
if(pre == nullptr) { // 第一个节点值
count = 1;
} else if (cur->val == pre->val) { // 与前一个节点值相同
++count;
} else { // 与前一个节点值不同
count = 1; // 节点值发生变化
}
pre = cur; //更新上一个节点
if (count > maxCnt) { // 如果计数大于最大值频率
res.clear(); // 清空res
maxCnt = count; // 更新最大频率
res.push_back(cur->val);
} else if (count == maxCnt) { // 如果和最大值相同,放进res中
res.push_back(cur->val);
}
searchBST(cur->right);
}
vector<int> findMode(TreeNode* root) {
searchBST(root);
return res;
}
};
236. 二叉树的最近公共祖先
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;
}
return left ? left : right;
}
};