二叉搜索树的最小绝对差
题目链接:leetcode530
思路:我的一个误区是默认了 查找的是相邻的节点之间的最小绝对差,题目问的是所有节点之间的。
基于二叉搜索树的特性,按照中序遍历则可以得到单调序列,进行相减查询即可。
class Solution {
public:
int res = INT_MAX;
TreeNode * prev = nullptr;
void traversal(TreeNode* root){
if(root==NULL) return;
traversal(root->left);
if(prev) res = min(res, root->val - prev->val);
prev = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return res;
}
};
二叉搜索树中的众数
题目链接:leetcode501
思路:通过中序遍历,可以将所有的子序列按照顺序排列,使用两个指针一前一后去累计所有相等数值的情况。
递归单步执行的逻辑:
- count的基数为1,因为只要有一个就代表它肯定至少有一个,但是因为双指针的原因,不会在累加中统计进去,所以需要初始设置为1.
- 当count> maxcount时,要将原本的res列表清空,并且同时更新maxCount。
- 当count值相等时,就把当前值Push进去即可。
class Solution {
public:
vector<int> res;
int maxCount = 0;
TreeNode * pre = nullptr;
int count = 1;
void traversal(TreeNode* root){
if(root==nullptr) return;
traversal(root->left);
if(pre){
if(root->val == pre->val){
count++;
}
else{
count = 1;
}
}
pre =root;
if(count == maxCount) res.push_back(root->val);
if(count > maxCount){
res.clear();
res.push_back(root->val);
maxCount = count;
}
traversal(root->right);
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return res;
}
};
二叉树的最近公共祖先
题目链接:leetcode236
思路:
- 最近公共祖先,是根据从叶子往根去查找的一个过程,递归遍历符合条件的只有后序遍历了。
- 满足最近公共祖先的情况有两种,一种是左右子树中分别包含了p和q两个树节点。
- 第二种情况是,某个子树中包含了其中一个节点,根节点是另外一个节点。
- 针对这两种情况做判断即可。
class Solution {
public:
TreeNode *ans = NULL;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q){
if(!root) return false;
bool lres = false, rres = false;
lres = dfs(root->left, p, q);
rres = dfs(root->right, p, q);
if((lres && rres) || (root->val == p->val || root->val == q->val) && (lres || rres)){
ans = root;
return true;
}
return lres || rres || root->val==p->val || root->val==q->val;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
dfs(root, p, q);
return ans;
}
};