Leetcode 530. 二叉搜索树的最小绝对差
thought:
二叉搜索树找第一第二大值的差值,使用中序遍历,由于要记录倒数第二大的值,考虑设置全局变量TreeNode* pre = NULL;
,时刻记录上一次递归的值
完整C++代码如下:
class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
if (cur == NULL)
return;
traversal(cur->left);
if (pre != NULL) {
result = min(result, cur->val - pre->val);
}
pre = cur;
traversal(cur->right);
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
Leetcode 501.二叉搜索树中的众数
thought:
和前一题思路大致相同
在Solution2中,存在以下问题:
- 错误的计数位置:在Solution2中,计数(
count
)的更新位置不正确。计数应该在检查前一个节点值与当前节点值是否相等之后进行更新。然而,在Solution2中,计数的更新发生在检查前一个节点是否为NULL之后。这会导致在处理第一个节点时无法正确地初始化计数器。 - 未处理最后一个节点:在Solution2的遍历中,对于最后一个节点,它的计数没有被正确地处理。在遍历结束后,最后一个节点的计数应该被检查并处理。
- 清空结果容器位置错误:在Solution2中,清空结果容器(
res
)的操作应该在发现当前计数(count
)大于最大计数(max_count
)时进行,而不是在发现当前节点值与前一个节点值不同时进行。 - 最大计数初始化错误:
max_count
在Solution2中被错误地初始化为INT_MIN
,这可能导致不正确的结果。应该初始化为0。
完整C++代码如下:
//wrong
class Solution2 {
public:
TreeNode* pre = NULL;
int max_count=INT_MIN;
int count=1;
vector<int> findMode(TreeNode* root) {
vector<int>res;
traversal(root,res);
return res;
}
void traversal(TreeNode* root,vector<int>&res){
if(!root)return;
if(root->left)traversal(root->left,res);
if(pre!=NULL){
if(pre->val==root->val){
count++;
}
else {
if(count>max_count){
res.clear();
res.push_back(pre->val);
max_count=count;
}else if(count==max_count){
res.push_back(pre->val);
}
count=1;
}
pre=root;
}
if(root->right)traversal(root->right,res);
}
};
//right
class Solution {
public:
TreeNode* pre = NULL;
int max_count = 0; // Initialize max_count to 0
int count = 1;
vector<int> findMode(TreeNode* root) {
vector<int> res;
traversal(root, res);
// Check for the count of the last node
if (count > max_count) {
res.clear();
res.push_back(pre->val);
} else if (count == max_count) {
res.push_back(pre->val);
}
return res;
}
void traversal(TreeNode* root, vector<int>& res){
if (!root) return;
if (root->left) traversal(root->left, res);
if (pre != NULL) {
if (pre->val == root->val) {
count++;
} else {
if (count > max_count) {
res.clear();
res.push_back(pre->val);
max_count = count;
} else if (count == max_count) {
res.push_back(pre->val);
}
count = 1;
}
}
pre = root;
if (root->right) traversal(root->right, res);
}
};
Leetcode 236. 二叉树的最近公共祖先
完整C++代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == q || root == p || root == NULL) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left == NULL) return right;
return left;
}
};