目录
530 二叉搜索树的最小绝对差
class Solution {
public:
TreeNode* preNode = NULL;
int MinAbs = INT_MAX;
void getMin(TreeNode* root){
if(root == NULL) return;
getMin(root->left);
if(preNode != NULL){
int tmp = root->val - preNode->val;
MinAbs = min(tmp, MinAbs);
}
preNode = root;
getMin(root->right);
}
int getMinimumDifference(TreeNode* root) {
getMin(root);
return MinAbs;
}
};
501 二叉搜索树中的众数
class Solution {
public:
void preorder(TreeNode* root, map<int, int> &m){
if(root == NULL) return;
m[root->val]++;
preorder(root->left, m);
preorder(root->right, m);
}
vector<int> findMode(TreeNode* root) {
map<int, int> m;
vector<int> result;
if(root == NULL) return result;
preorder(root, m);
int max = 0;
for(map<int, int>::iterator it = m.begin(); it != m.end(); it++){
if(max < it->second){
max = it->second;
result.clear();
result.push_back(it->first);
}else if(max == it->second){
result.push_back(it->first);
}
}
return result;
}
};
236 二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL)
return root;
if (root->val == p->val || root->val == q->val) {
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{
return NULL;
}
}
};