当前位置:网站首页>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
边栏推荐
- Resource packaging dependency tree
- GoLand debug go use - white record
- L2-023 图着色问题 (25 分)(图的遍历)
- Star Trek强势来袭 开启元宇宙虚拟与现实的梦幻联动
- [indexof] [lastIndexOf] [split] [substring] usage details
- Error: cannot find or load main class
- 单片机数码管秒表
- 员工试用期转正申请书(泸州老窖)
- Flink reads MySQL and PgSQL at the same time, and the program will get stuck without logs
- 微信:获取单个标签所有人
猜你喜欢
PLC的点表(寄存器地址和点表定义)破解探测方案--方便工业互联网数据采集
1099 建立二叉搜索树 (30 分)
Strength comparison vulnerability of PHP based on hash algorithm
在sqli-liabs学习SQL注入之旅(第十一关~第二十关)
Solidity 问题汇总
Summary of solid problems
Matlab draw five-star red flag
L2-024 tribe (25 points) (and check the collection)
深度学习框架中的自动微分及高阶导数
Notes on xctf questions
随机推荐
搞不懂时间、时间戳、时区,快来看这篇
Withholding agent
js 原型链的深入
ONEFLOW learning notes: from functor to opexprinter
Project upload part
是否同一棵二叉搜索树 (25 分)
Go language self-study series | golang structure as function parameter
Applet in wechat and app get current ()
npm ERR! network
数字政府建设中政务中台中的技术创新点
在sqli-liabs学习SQL注入之旅(第十一关~第二十关)
How to read excel table to database
调包求得每个样本的k个邻居
Chris LATTNER, father of llvm: the golden age of compilers
Taxable income
LeetCode_ DFS_ Medium_ 1254. Count the number of closed islands
企业微信应用授权/静默登录
Judgment on heap (25 points) two insertion methods
Download and install bashdb
Harbor enterprise image management system