Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

   1
\
2
/
2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

这道题让我们求二分搜索树中的众数,这里定义的二分搜索树中左根右结点之间的关系是小于等于的,有些题目中是严格小于的,所以一定要看清题目要求。所谓的众数就是出现最多次的数字,可以有多个,那么这道题比较直接点思路就是利用一个哈希表来记录数字和其出现次数之前的映射,然后维护一个变量mx来记录当前最多的次数值,这样在遍历完树之后,根据这个mx值就能把对应的元素找出来。那么用这种方法的话就不需要用到二分搜索树的性质了,随意一种遍历方式都可以,下面我们来看递归的中序遍历的解法如下:

解法一:

class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int mx = ;
unordered_map<int, int> m;
inorder(root, m, mx);
for (auto a : m) {
if (a.second == mx) {
res.push_back(a.first);
}
}
return res;
}
void inorder(TreeNode* node, unordered_map<int, int>& m, int& mx) {
if (!node) return;
inorder(node->left, m, mx);
mx = max(mx, ++m[node->val]);
inorder(node->right, m, mx);
}
};

下面这种解法是上面方法的迭代形式,也是用的中序遍历的方法,有兴趣的童鞋可以实现其他的遍历方法:

解法二:

class Solution {
public:
vector<int> findMode(TreeNode* root) {
if (!root) return {};
vector<int> res;
TreeNode *p = root;
stack<TreeNode*> s;
unordered_map<int, int> m;
int mx = ;
while (!s.empty() || p) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
mx = max(mx, ++m[p->val]);
p = p->right;
}
for (auto a : m) {
if (a.second == mx) {
res.push_back(a.first);
}
}
return res;
}
};

题目中的follow up说了让我们不用除了递归中的隐含栈之外的额外空间,那么我们就不能用哈希表了,不过这也不难,由于是二分搜索树,那么我们中序遍历出来的结果就是有序的,这样我们只要比较前后两个元素是否相等,就等统计出现某个元素出现的次数,因为相同的元素肯定是都在一起的。我们需要一个结点变量pre来记录上一个遍历到的结点,然后mx还是记录最大的次数,cnt来计数当前元素出现的个数,我们在中序遍历的时候,如果pre不为空,说明当前不是第一个结点,我们和之前一个结点值比较,如果相等,cnt自增1,如果不等,cnt重置1。如果此时cnt大于了mx,那么我们清空结果res,并把当前结点值加入结果res,如果cnt等于mx,那我们直接将当前结点值加入结果res,然后mx赋值为cnt。最后我们要把pre更新为当前结点,参见代码如下:

解法三:

class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int mx = , cnt = ;
TreeNode *pre = NULL;
inorder(root, pre, cnt, mx, res);
return res;
}
void inorder(TreeNode* node, TreeNode*& pre, int& cnt, int& mx, vector<int>& res) {
if (!node) return;
inorder(node->left, pre, cnt, mx, res);
if (pre) {
cnt = (node->val == pre->val) ? cnt + : ;
}
if (cnt >= mx) {
if (cnt > mx) res.clear();
res.push_back(node->val);
mx = cnt;
}
pre = node;
inorder(node->right, pre, cnt, mx, res);
}
};

下面这种方法是上面解法的迭代写法,思路基本相同,可以参考上面的讲解,参见代码如下:

解法四:

class Solution {
public:
vector<int> findMode(TreeNode* root) {
if (!root) return {};
vector<int> res;
TreeNode *p = root, *pre = NULL;
stack<TreeNode*> s;
int mx = , cnt = ;;
while (!s.empty() || p) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
if (pre) {
cnt = (p->val == pre->val) ? cnt + : ;
}
if (cnt >= mx) {
if (cnt > mx) res.clear();
res.push_back(p->val);
mx = cnt;
}
pre = p;
p = p->right;
}
return res;
}
};

类似题目:

Binary Tree Inorder Traversal

参考资料:

https://discuss.leetcode.com/topic/77335/proper-o-1-space

https://discuss.leetcode.com/topic/77080/c-dfs-time-o-n-space-o-n

https://discuss.leetcode.com/topic/77077/ugly-but-straight-forward-java-solution

https://discuss.leetcode.com/topic/77330/java-4ms-beats-100-extra-o-1-solution-no-map

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数的更多相关文章

  1. 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)

    [LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...

  2. 【一天一道LeetCode】#99. Recover Binary Search Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Two ele ...

  3. LeetCode Find Mode in Binary Search Tree

    原题链接在这里:https://leetcode.com/problems/find-mode-in-binary-search-tree/#/description 题目: Given a bina ...

  4. 【LeetCode】 99. Recover Binary Search Tree [Hard] [Morris Traversal] [Tree]

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  5. 【LeetCode】1008. Construct Binary Search Tree from Preorder Traversal 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  6. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  7. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  8. 【LeetCode OJ】Recover Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...

  9. 【一天一道LeetCode】#98. Validate Binary Search Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

随机推荐

  1. phpcms v9 搜索结果列表页时间显示1970问题解决方案

    对于喜欢用phpcms v9 的小伙伴来说,在调用时间时,总会出现时间1970这样的问题,对于这个问题,网上的说法很多,内容页时间显示通常不会问题,搜索结果页就不行了,通过总结,发现使用{format ...

  2. jdk 环境配置踩坑

    其实在网上已经有很多环境配置的介绍了.不过我还是想用切身经历告诉大家这里面可能遇到的坑. 首先,先给大家讲一下JAVA_HOME,path,CLASSPATH JAVA_HOME 指向的是JDK的安装 ...

  3. .Net开发之旅(一个年少轻狂的程序员的感慨)

    高端大气上档次.这次当时一个身为懵懂初中生的我对程序员这一职位的描述.那时虽不是随处都能看到黑客大军的波及,但至少是知道所谓的黑客爸爸的厉害,一言不合说被黑就被黑.对于懵懂的我那是一种向往.自己也曾想 ...

  4. java Classpath 的解读

    在了解java的classpath之前先来看看java的运行机制  1.首先是编译,将.java文件编译成虚拟机认识的二进制文件.这个过程需要的命令是javac  可以在jdk的bin目录中找到,ja ...

  5. 福州大学W班-alpha冲刺评分

    作业链接 https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/1159 作业要求 1.前期准备 阅读学习&l ...

  6. beta冲刺4

    昨天的问题: 我的社团数据库表项的处理,代码修改后结果无法显示. 帖子内容无法显示出来. 首页图像未替换 登陆整合没有完成 今天的完成: 服务器部署成功 页面背景修改.(已上传,未确认实装.) 任务截 ...

  7. 详谈C++虚函数表那回事(一般继承关系)

    沿途总是会出现关于C++虚函数表的问题,今天做一总结: 1.什么是虚函数表: 虚函数(Virtual Function)是通过一张虚函数表(Virtual Table)来实现的.简称为V-Table. ...

  8. surging教学视频资源汇总

    surging是什么 surging 是一个分布式微服务框架,提供高性能RPC远程服务调用,采用Zookeeper.Consul作为surging服务的注册中心,集成了哈希,随机,轮询.压力最小优先作 ...

  9. nyoj 数的长度

    描述 N!阶乘是一个非常大的数,大家都知道计算公式是N!=N*(N-1)······*2*1.现在你的任务是计算出N!的位数有多少(十进制)?   输入 首行输入n,表示有多少组测试数据(n<1 ...

  10. nyoj 还是回文

    还是回文 时间限制:2000 ms | 内存限制:65535 KB 难度:3 描述 判断回文串很简单,把字符串变成回文串也不难.现在我们增加点难度,给出一串字符(全部是小写字母),添加或删除一个字符, ...