代码随想录算法训练营第十八天|530 二叉搜索树的最小绝对差、501 二叉搜索树中的众数、236 二叉树的最近公共祖先

一、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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值