530. 二叉搜索树的最小绝对差
详解
/**
* 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 {
public:
TreeNode* pre = NULL;
int result = INT_MAX;
//中序遍历是递增的
int getMinimumDifference(TreeNode* root) {
if(root == NULL) return -1;
getMinimumDifference(root->left);
if(pre != NULL){
result = min(result, abs(pre->val - root->val));
}
pre = root;
getMinimumDifference(root->right);
return result;
}
};
501. 二叉搜索树中的众数
/**
* 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 {
public:
vector<int> result;
TreeNode* pre = NULL;
int count=0, max_count=0;
//中序遍历递增
vector<int> findMode(TreeNode* root) {
if(!root) return {};
findMode(root->left);
if(pre == NULL){
count = 1;
}else if(pre->val == root->val){//连续相同
count++;
}else{
count = 1;
}
if (count == max_count) { // 如果和最大值相同,放进result中
result.push_back(root->val);
}
pre = root;
if (count > max_count) { // 如果计数大于最大值频率
max_count = count; // 更新最大频率
result.clear(); // 很关键的一步,不要忘记清空result,之前result里的元素都失效了
result.push_back(root->val);
}
findMode(root->right);
return result;
}
};
236. 二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q || root == NULL) 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; //有1个是NULL
}
};