● 530.二叉搜索树的最小绝对差
● 501.二叉搜索树中的众数
● 236. 二叉树的最近公共祖先
530. 二叉搜索树的最小绝对差
可以按照中序遍历构造数组,然后去求,但是这样和咸鱼有什么区别
所以选择使用双指针
class Solution {
int res = INT_MAX;
TreeNode* pre = nullptr;
void getMinDif(TreeNode* root) {
if(root == nullptr) return;
getMinDif(root->left);
if(pre != nullptr) res = min(res, abs(pre->val - root->val));
pre = root;
getMinDif(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
getMinDif(root);
return res;
}
};
501. 二叉搜索树中的众数
这个方法好像比较咸鱼
class Solution {
int maxcnt = 0;
void serchBST(TreeNode* root, unordered_map<int, int>& hash) {
if(root == nullptr) return;
serchBST(root->left, hash);
hash[root->val]++;
maxcnt = max(maxcnt, hash[root->val]);
serchBST(root->right, hash);
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> hash;
serchBST(root, hash);
vector<int> res;
for(auto it = hash.begin(); it != hash.end(); ++it) {
if(it->second == maxcnt) {
res.push_back(it->first);
}
}
return res;
}
};
既然是搜索树,所以相同元素肯定挨着
舒服了!
class Solution {
int curcnt = 0;
int maxcnt = 0;
TreeNode* pre = nullptr;
vector<int> res;
void serchBST(TreeNode* root) {
if(root == nullptr) return;
serchBST(root->left);
if(pre == nullptr) {
curcnt = 1;
} else if (pre->val == root->val) {
curcnt++;
} else {
curcnt = 1;
}
if(curcnt == maxcnt) {
res.push_back(root->val);
}
if(curcnt > maxcnt) {
maxcnt = curcnt;
res.clear();
res.push_back(root->val);
}
pre = root;
serchBST(root->right);
}
public:
vector<int> findMode(TreeNode* root) {
serchBST(root);
return res;
}
};
236. 二叉树的最近公共祖先
思路是对的,码起来有点问题,看了看随想录
用后序遍历(符合从下到上的逻辑)
递归函数有返回值就是要遍历某一条边,但有返回值也要看如何处理返回值! 如果递归函数有返回值,如何区分要搜索一条边,还是搜索整个树呢?
在递归函数有返回值的情况下:如果要搜索一条边,递归函数返回值不为空的时候,立刻返回,如果搜索整个树,直接用一个变量left、right接住返回值,这个left、right后序还有逻辑处理的需要,也就是后序遍历中处理中间节点的逻辑(也是回溯)。
其实比较好理解,这个题需要遍历整个树
值得回味
这个题就是,左右遍历的结果我们需要保存,来做判断
而左右结点为空就代表没找到那俩结点之一,
这是一层一层返回,直到返回到那个公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};