1、二叉搜索树的最小绝对差
二叉搜索树的最小绝对差
class Solution {
public:
int minValue = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* root) {
if (!root) return;
traversal(root->left);
if (pre) minValue = min(minValue, root->val - pre->val);
pre = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return minValue;
}
};
2、二叉搜索树的众数
二叉搜索树的众数
class Solution {
public:
vector<int> result;
int maxCount;
int count;
TreeNode* pre = NULL;
void searchBST(TreeNode* root) {
if (!root) return ;
searchBST(root->left);
if (pre == NULL) {
count = 1;
maxCount = 1;
}
if (pre != NULL && pre->val == root->val) {
count++;
} else {
count = 1;
}
if (maxCount == count) {
result.push_back(root->val);
}
if (maxCount < count) {
maxCount = count;
result.clear();
result.push_back(root->val);
}
pre = root;
searchBST(root->right);
}
vector<int> findMode(TreeNode* root) {
searchBST(root);
return result;
}
};
3、二叉树的最近公共祖先
二叉树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL) return NULL;
if (root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (!left && right) return right;
else if (left && !right) return left;
else return NULL;
}
};