530.二叉搜索树的最小绝对差
首先将二叉树(二叉搜索树,左边节点小于右边节点)的值输入到数组,使用中序,可以得到一个升序数组,再进行前后比较。
class Solution {
public:
vector<int> res;
void traversal(TreeNode *root){
if(root==nullptr) return;
traversal(root->left);
res.push_back(root->val);
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
if(res.size()<2) return 0;
int result=INT_MAX;
for(int i=1;i<res.size();i++){
result=min(result,res[i]-res[i-1]);
}
return result;
}
};
501.二叉搜索树中的众数
理解了用map来存放对应值存在的个数,但是没懂如何遍历出出现次数最多的值,并且众数不止一个。这题需要反复做,知识点多。 也可以先放入数组,再统计,类似上题的做法。
class Solution {
private:
void searchBST(TreeNode* cur, unordered_map<int, int>& map) { // 前序遍历
if (cur == NULL) return ;
map[cur->val]++; // 统计元素频率
searchBST(cur->left, map);
searchBST(cur->right, map);
return ;
}
bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> map; // key:元素,value:出现频率
vector<int> result;
if (root == NULL) return result;
searchBST(root, map);
vector<pair<int, int>> vec(map.begin(), map.end());
sort(vec.begin(), vec.end(), cmp); // 给频率排个序
result.push_back(vec[0].first);
for (int i = 1; i < vec.size(); i++) {
// 取最高的放到result数组中
if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
else break;
}
return result;
}
};
236. 二叉树的最近公共祖先
从下往上遍历想到用后序遍历。
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 left;
else if (left == NULL && right != NULL) return right;
else return NULL;
}
};