530-二叉搜索树的最小绝对差
题目链接:LeetCode-530简单
思考:利用中序遍历存储数组,进行比较差值
class Solution {
private:
vector<int> vec;
void traversal(TreeNode* root){
if(root==NULL) return;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
vec.clear();
traversal(root);
if(vec.size()<2) return 0;
int result = INT_MAX;
for(int i=1;i<vec.size();i++){
result=min(result,vec[i]-vec[i-1]);
}
return result;
}
};
501-二叉搜索树的最小绝对差
题目链接:LeetCode-501简单
思考:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
class Solution {
private:
int maxCount;
int count;
TreeNode* pre;
vector<int> result;
void searchBST(TreeNode* cur){
if(cur==NULL) return;
searchBST(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=count;
result.clear();
result.push_back(cur->val);
}
searchBST(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
count=0;
maxCount=0;
TreeNode*pre=NULL;
result.clear();
searchBST(root);
return result;
}
};
236-二叉搜索树的最小绝对差
题目链接:LeetCode-236中等
思考:
- 如果left 和 right都不为空,说明此时root就是最近公共节点。这个比较好理解
- 如果left为空,right不为空,就返回right,说明目标节点是通过right返回的,反之依然
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;
}
//if(left==NULL) return right;
//return left;
}
};