Leetcode 530二叉搜索树的最小绝对值
刚开始觉得最小绝对值一定出现在一个节点与它的左右子节点,后来发现不是专业。二叉搜索树的处理,可以使用中序遍历得到一个有序数组进行处理。
class Solution {
public:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* node){
if(node == NULL){
return;
}
traversal(node -> left);
if(pre != NULL){
result = min(result, abs(node -> val - pre -> val));
}
pre = node;
traversal(node -> right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
Leetcode 501 二叉搜索树的众数
首先,可以先遍历一边二叉树,并使用一个map记录下树中元素出现的次数,再从unordered_map中得到众数。其次,可以利用二叉搜索树的特性,使用中序遍历和双指针来模拟对有序数组的众数求取过程。
class Solution {
public:
vector<int> result;
int count = 0;
int maxCount = 0;
TreeNode* pre = NULL;
void searchBT(TreeNode* cur){
if(cur == NULL) {return;}
searchBT(cur -> left);
if(pre == NULL){
count = 1;;
}else if(pre -> val == cur -> val){
count++;
}else if(pre -> val != cur -> val){
count = 1;
}
pre = cur;
if(count == maxCount){
result.push_back(cur -> val);
}
if(count > maxCount){
maxCount = count;
result.clear();
result.push_back(cur -> val);
}
searchBT(cur -> right);
return;
}
vector<int> findMode(TreeNode* root) {
searchBT(root);
return result;
}
};
Leetcode 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 right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
};