代码随想录算法训练营第二十天|530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
思路:由于是二叉搜索树,先用中序遍历将节点存入数组中,再遍历数组相邻元素即可。
class Solution {
public:
void qianxu(TreeNode* root,vector<int> &v){
if(root->left)qianxu(root->left,v);
v.push_back(root->val);
if(root->right)qianxu(root->right,v);
}
int getMinimumDifference(TreeNode* root) {
vector<int> v;
qianxu(root,v);
int result=abs(v[1]-v[0]);
for(int i=2;i<v.size();i++ ){
if(result>abs(v[i]-v[i-1]))result=abs(v[i]-v[i-1]);
}
return result;
}
};
501.二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
class Solution {
public:
void qianxu(TreeNode* root,map<int,int>& m){
if(root->left)qianxu(root->left,m);
m[root->val]++;
if(root->right)qianxu(root->right,m);
}
vector<int> findMode(TreeNode* root) {
map<int,int>m;
qianxu(root,m);
vector<int>result;
int max=0;
for(map<int,int>::iterator it=m.begin();it!=m.end();it++){
if(it->second>=max)max=it->second;
}
for(map<int,int>::iterator it=m.begin();it!=m.end();it++){
if(it->second==max)result.push_back(it->first);
}
return result;
}
};
236.二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
思路:本题难点在于如何对二叉树进行自底向上的查找,即回溯。方法就是后序遍历。
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;
}
}
};
浙公网安备 33010602011771号