当前位置:网站首页>501. 二叉搜索树中的众数
501. 二叉搜索树中的众数
2022-04-23 09:04:00 【yitahutu79】
给你一个含重复值的二叉搜索树(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;
}
版权声明
本文为[yitahutu79]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40713201/article/details/124357739
边栏推荐
- 考研线性代数常见概念、问题总结
- Share the office and improve the settled experience
- MySQL小練習(僅適合初學者,非初學者勿進)
- 小女孩行走
- 是否同一棵二叉搜索树 (25 分)
- Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
- 还原二叉树 (25 分)
- The most concerned occupations after 00: civil servants ranked second. What was the first?
- Applet in wechat and app get current ()
- Number theory to find the sum of factors of a ^ B (A and B are 1e12 levels)
猜你喜欢
Valgrind et kcachegrind utilisent l'analyse d'exécution
Download and install bashdb
Brief steps to build a website / application using flash and H5
Redis Desktop Manager for Mac
Idea package jar file
Summary of solid problems
valgrind和kcachegrind使用運行分析
OneFlow学习笔记:从Functor到OpExprInterpreter
L2-022 重排链表 (25 分)(map+结构体模拟)
调包求得每个样本的k个邻居
随机推荐
The crawler returns null when parsing with XPath. The reason why the crawler cannot get the corresponding element and the solution
Redis Desktop Manager for Mac
PCTP考试经验分享
Arbre de dépendance de l'emballage des ressources
Wechat: get the owner of a single tag
Valgrind and kcache grind use run analysis
Restore binary tree (25 points)
To remember the composition ~ the pre order traversal of binary tree
[Luke V0] verification environment 2 - Verification Environment components
请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨
小女孩行走
资源打包关系依赖树
K210 learning notes (II) serial communication between k210 and stm32
GoLand debug go use - white record
Common errors of VMware building es8
dataBinding中使用include
Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
还原二叉树 (25 分)
BK3633 规格书
Research purpose, construction goal, construction significance, technological innovation, technological effect