这题我想了巨久也没想出来…看到卡哥一句话:
遇到在二叉搜索树上求什么最值啊,差值之类的,就把它想成在一个有序数组上求最值,求差值,这样就简单多了。
其实除了这个办法,也可以把中序遍历的值全部存在一个数组里,求这个数组元素差值的最小值。遇到遍历二叉树,一定要想到中序遍历(有序数组)!
class Solution {
private:
int ans = INT_MAX;
TreeNode* pre = nullptr;
void dfs(TreeNode* root){
if(!root) return;
dfs(root->left);
if(pre){
ans = min(ans, root->val - pre->val);
}
pre = root;
dfs(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
dfs(root);
return ans;
}
};
有了上一题做铺垫,这题就显得很简单了。
class Solution {
private:
vector<int> tmp;
void dfs(TreeNode* root){
if(!root) return;
dfs(root->left);
tmp.push_back(root->val);
dfs(root->right);
}
public:
vector<int> findMode(TreeNode* root) {
dfs(root);
vector<int> res;
res.push_back(tmp[0]);
if(!root->left && !root->right) return res;
int count = 1, maxCount = 1;
for(int i = 1; i < tmp.size(); ++i){
if(tmp[i-1] == tmp[i]){
++count;
}else{
count = 1;
}
if(count > maxCount){
maxCount = count;
res.clear();
res.push_back(tmp[i]);
}else if(count == maxCount){
res.push_back(tmp[i]);
}
}
return res;
}
};
早上起来,又写了一个不用array的二叉树双指针的解法。
class Solution {
private:
vector<int> res;
TreeNode* prev = nullptr;
int max = 1;
int count = 1;
void dfs(TreeNode* root){
if(!root) return;
dfs(root->left);
if(prev != nullptr && root->val == prev->val){
++count;
}else{
count = 1;
}
if(count > max){
max = count;
res.clear();
res.push_back(root->val);
}else if(count == max){
res.push_back(root->val);
}
prev = root;
dfs(root->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
dfs(root);
return res;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q || !root) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
//left, right只能是p, q或者null.
if(left != nullptr && right != nullptr) return root;
if(left == nullptr && right != nullptr){
return right;
}else if(left != nullptr && right == nullptr){
return left;
}else{
return nullptr;
}
}
};
今日感悟:
- 遇到二叉搜索树就想中序遍历数组
- 遍历一枝树和遍历整个树的区别
if(方法(left)) return;
if(方法(right)) return;
vs.
left = 方法;
right = 方法;
- 做题先考虑用什么遍历方法!后序遍历还是中序遍历?后序遍历和回溯相似!如果用后序,树打开以后,要看打开前的条件判断来写代码!
文章介绍了如何利用二叉搜索树的性质解决求最小差值、找众数(模式)以及寻找最低公共祖先的问题。主要策略包括中序遍历、深度优先搜索(DFS)和双指针方法。对于二叉搜索树,转换为处理有序数组的思想有助于简化问题。
824

被折叠的 条评论
为什么被折叠?



