文档讲解: 代码随想录
视频讲解:二叉搜索树中,需要掌握如何双指针遍历!| LeetCode:530.二叉搜索树的最小绝对差_哔哩哔哩_bilibili
第20天,一刻不得闲咯。
思路:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};
501.二叉搜索树中的众数
思路:
class solution{
private:
TreeNode* pre = NULL;
int count = 0, maxcount = 0;
vector<int> result;
void traversal(TreeNOde* cur){
if(cur == NULL) return;
traversal(cur->left);
if(pre == NULL) 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){//发现新的元素频率,就更新maxcount,并释放之前存储的结果
maxcount = count;
result.clear();
result.push_back(cur->val);//将新的元素频率放入结果集
}
traversal(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root){
count = 0;
maxcount = 0;
pre = NULL;
result.clear();
traversal(root);
return result;
}
};
思路:
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 && right != NULL) return right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
};
例行总结:这才一半进度不到,不可懈怠。