二叉搜索树中节点之差的最小值
转化为有序数组写法

数组越界
代码
class Solution {
private:
vector<int> vec;
public:
void traversal(TreeNode* root) {
if (root == NULL)
return;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
vec.clear();
traversal(root);
if(vec.size()<2) return 0;
int result = INT_MAX;
for (int i = 1; i < vec.size(); i++)
result = min(result, vec[i] - vec[i-1]);
return result;
}
};
双指针写法
class Solution{
private:
int result=INT_MAX;
TreeNode* pre =NULL;
public:
void traversal(TreeNode* curr){
//int result=INT_MAX;
if(curr==NULL) return;
traversal(curr->left);
if(pre!=NULL){result=min(result,curr->val-pre->val);
}pre =curr;
traversal(curr->right);
}
int getMinimumDifference(TreeNode* root){
traversal(root);
return result;//类内函数可以访问该类的所有成员变量
}
};
找出二叉搜索树中的众数
题目理解
如果根节点为空,那么返回NULL;
可能存在有两个数值在二叉树中出现的次数相同;
二叉搜索树,先转化为有序数组,然后用一个变量累加相同值出现的次数,如果有更大的出现就覆盖掉之前的。但是如果有两个值出现次数相同就会漏掉之前的。
代码实现
class Solution {
private:
vector<int> res;
TreeNode* pre = NULL;
int maxCount = 0;
int count;
public:
void traversal(TreeNode* curr) {
if (curr == NULL) {
return;
}
traversal(curr->left);
if (pre == NULL) {
count = 1;
} else if (pre->val == curr->val) {
count++;
} else {
count = 1;
}
pre = curr;
if (count == maxCount) {
res.push_back(curr->val);
}
// maxCount = count;
if (count > maxCount) {
maxCount = count;
res.clear();
res.push_back(curr->val);
}
traversal(curr->right);
return;
}
vector<int> findMode(TreeNode* root) {
pre = NULL;
count = 0;
maxCount = 0;
res.clear();
traversal(root);
return res;
}
};
二叉树的最近公共祖先
题目理解
给出距两个节点最近的根。
思路
如果给出的两个节点相同并且二叉树中存在多个该值。
代码实现
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return root;
if(root==p||root==q) 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 left;
if(left==NULL&&right!=NULL) return right;
else return NULL;
}
};
总结
这道题的思路就是一层一层返回根节点。把给定节点的祖先一层一层更新为节点(节点的指针)。
最后一定存在一个根节点,它的左子树和右子树分别是p和q.
如果p是q的一个孩子,那么返回的值就是q.即我们要求的根节点。
不懂为什么一定要遍历整棵树。
浙公网安备 33010602011771号