zl程序教程

您现在的位置是:首页 >  其他

当前栏目

501. 二叉搜索树中的众数

搜索 二叉 树中 众数
2023-09-27 14:26:25 时间

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树

示例 1:
在这里插入图片描述

输入:root = [1,null,2,2]
输出:[2]
示例 2:

输入:root = [0]
输出:[0]

提示:

树中节点的数目在范围 [1, 104] 内
-105 <= Node.val <= 105

/**
 * 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().
 */
struct TreeNode *pre;
int cnt, max_cnt;

void inorder(struct TreeNode *root, int *ret, int *pn) {
    if (root == NULL) return;
    inorder(root->left, ret, pn);
    if (pre == NULL || pre->val != root->val) cnt = 1;
    else cnt += 1;
    pre = root;
    if (cnt == max_cnt) {
        ret[(*pn)++] = root->val;
    } else if (cnt > max_cnt) {
        max_cnt = cnt;
        ret[0] = root->val;
        *pn = 1;
    }
    inorder(root->right, ret, pn);
    return;
}

int* findMode(struct TreeNode* root, int* returnSize){
    int *ret = (int *)malloc(sizeof(int) * 10000);
    *returnSize = 0;
    pre = NULL;
    cnt = 0;
    max_cnt =  -1;
    inorder(root, ret, returnSize);
    return ret;
}