一、530 二叉搜索树的最小绝对差
class Solution {
public:
int result = INT_MAX;//要找最小值,就要初始化为最大值
//采用中序遍历+双指针的方法
struct TreeNode*pre = NULL;//指向当前遍历节点的前一个节点
int getMinimumDifference(struct TreeNode* root) {
//root是遍历当前节点
if(root==NULL)
return 0;
//左
getMinimumDifference(root->left);
//中
if(pre!=NULL){
result = result>(root->val-pre->val)?root->val-pre->val:result;
}
pre = root;//采用左子树递归的回溯逻辑
//右
getMinimumDifference(root->right);
return result;
}
};
二、501 二叉搜索树中的众数
void inorder(struct TreeNode*root,int *tmp,int *count){
if(root == NULL)
return;
inorder(root -> left,tmp,count);
tmp[(*count)++] = root -> val;
inorder(root -> right,tmp,count);
}
int* findMode(struct TreeNode* root, int* returnSize) {
int *tmp = (int*)malloc(sizeof(int)*10001);
int count = 0;
inorder(root,tmp,&count);//中序遍历得到数组
int max = 1,cur = 1;
//寻找数组中出现最多的次数
for(int i = 1; i < count;i++){
if(tmp[i] == tmp[i-1]){
cur++;
}
else{
cur = 1;
}
if(cur > max){
max = cur;
}
}
//开辟一个数组,返回结果数组
int *ret = (int*)malloc(sizeof(int)*count);
int flag = 0;
//所有结点值出现次数为1的情况
if(max == 1){
(*returnSize) = count;
return tmp;
}
//初始化cur
cur = 1;
for(int i = 1; i < count; i++){
if(tmp[i] == tmp[i-1]){
cur++;
}
else{
cur = 1;
}
if(cur == max){
ret[flag++] = tmp[i];
}
}
(*returnSize) = flag;
return ret;
}
三、236 二叉树的最近公共祖先
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root == NULL)
return NULL;
if(root == p||root == q)
return root;
//后序遍历
//左
struct TreeNode* left = lowestCommonAncestor(root->left,p,q);
//右
struct 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
return NULL;
}