llllmz

导航

501. 二叉搜索树中的众数c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int max,sum,pre;

void updata(int* temp,int num,int* returnSize){
    if(num==pre){
        sum++;
    }else{
        pre=num;
        sum=1;
    }
    if(sum==max){
        temp[*returnSize]=num;
        (*returnSize)++;
    }
    if(sum>max){
        max=sum; 
        temp[0]=num;
        *returnSize=1;  
    }
}


void inorder(struct TreeNode* root,int* temp,int* returnSize){
    if(!root) return ;
    inorder(root->left,temp,returnSize);
    updata(temp,root->val,returnSize);
    inorder(root->right,temp,returnSize);
}

int* findMode(struct TreeNode* root, int* returnSize) {
    max=INT_MIN,sum=0,pre=INT_MIN;
    int* temp=(int*)malloc(sizeof(int)*10000);
    *returnSize=0;
    inorder(root,temp,returnSize);
    return temp;
}

结果:

posted on 2024-03-14 16:12  神奇的萝卜丝  阅读(15)  评论(0)    收藏  举报