【LeetCode】501. Find Mode in Binary Search Tree 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/find-mode-in-binary-search-tree/#/description
题目描述
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).
题目大意
找出一个BST中出现次数最多的节点们。
解题方法
见到BST就想到中序遍历。这个题中的BST是可以包含相同的元素的,题目的要求就是找出相同的元素出现次数最多的是哪几个。那么就可以先进行中序遍历得到有序的排列,如果两个相邻的元素相同,那么这个就是连续的,找出连续最多的即可。题目思路就是BST的中序遍历加上最长连续相同子序列。
如果使用附加空间的话,可以使用hash保存每个节点出现的次数。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
self.count = collections.Counter()
self.inOrder(root)
freq = max(self.count.values())
res = []
for item, c in self.count.items():
if c == freq:
res.append(item)
return res
def inOrder(self, root):
if not root:
return
self.inOrder(root.left)
self.count[root.val] += 1
self.inOrder(root.right)
题目建议不要用附加空间hash等,方法是计算了两次,一次是统计最大的模式出现的次数,第二次的时候构建出来了数组,然后把出现次数等于最大模式次数的数字放到数组的对应位置。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int[] findMode(TreeNode root) {
inOrder(root);
modes = new int[modeCount];
currCount = 0;
modeCount = 0;
inOrder(root);
return modes;
}
int currVal = 0;
int currCount = 0;
int maxCount = 0;
int modeCount = 0;
int[] modes;
public void handleValue(int val){
if(currVal != val){
currVal = val;
currCount = 0;
}
currCount++;
if(currCount > maxCount){
maxCount = currCount;
modeCount = 1;
}else if (currCount == maxCount){
if(modes != null){
modes[modeCount] = currVal;
}
modeCount++;
}
}
public void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
handleValue(root.val);
inOrder(root.right);
}
}
日期
2017 年 5 月 3 日
2018 年 11 月 23 日 —— 这就星期五了??
【LeetCode】501. Find Mode in Binary Search Tree 解题报告(Python)的更多相关文章
- 【LeetCode】669. Trim a Binary Search Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- LeetCode: Convert Sorted List to Binary Search Tree 解题报告
Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in as ...
- LeetCode: Convert Sorted Array to Binary Search Tree 解题报告
Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending ord ...
- 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)
[LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...
- 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)
[LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...
- 35. leetcode 501. Find Mode in Binary Search Tree
501. Find Mode in Binary Search Tree Given a binary search tree (BST) with duplicates, find all the ...
- LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred ...
- LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告
https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest ...
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...
随机推荐
- 日常Java 2021/11/21
Java文档注释 Java支持三种注释方式.前两种分别是Ⅱ和/产*,第三种被称作说明注释,它以产开始,以*I结束.说明注释允许你在程序中嵌入关于程序的信息.你可以使用javadoc工具软件来生成信息, ...
- 23. 关于Ubuntu中Could not get lock /var/lib/dpkg/lock解决方案
原文:https://blog.csdn.net/u011596455/article/details/60322568 版权声明:本文为博主原创文章,转载请附上博文链接! 在Ubuntu中,有时候运 ...
- 如何将List集合中相同属性的对象合并
在实际的业务处理中,我们经常会碰到需要合并同一个集合内相同属性对象的情况,比如,同一个用户短时间内下的订单,我们需要将各个订单的金额合并成一个总金额.那么用lambda表达式和HashMap怎么分别处 ...
- 【编程思想】【设计模式】【其他模式】graph_search
Python版 https://github.com/faif/python-patterns/blob/master/other/graph_search.py #!/usr/bin/env pyt ...
- “==” 和 equals()的区别
※ "==" 和 equals()的区别 ※ == :比较. 基本数据类型比较的是值:. 引用类型比较的是地址值. ※ equals(Object o):1)不能比较基本数据类型, ...
- matplotlib如何绘制直方图、条形图和饼图
1 绘制直方图: import matplotlib.pyplot as plt import numpy as np import matplotlib def hist1(): # 设置matpl ...
- 使用jdbc,查询数据库数据,并将其封装为对象输出
package cn.itcast.jdbc;import cn.itcast.domain.User;import java.sql.*;import java.util.ArrayList;imp ...
- 【科研工具】流程图软件Visio Pro 2019 详细安装破解教程
[更新区] 安装教程我下周会在bilibili上传视频,这周事情太多暂时先不弄. [注意] 安装Visio需要和自己的Word版本一样,这里因为我的Word是学校的正版2019(所以学校为什么正版没买 ...
- 关于synchronize与lock的区别
参考文献:https://www.cnblogs.com/cloudblogs/p/6440160.html 一.synchronize修饰不同代码都是锁住了什么? 大家都知道synchronize可 ...
- 如何优雅正确地通过interrupt方法中断线程
为什么废弃Thread的stop函数? 简单来说就是stop方法中断线程太过暴力随意,且会是否线程持有的锁,会导致线程安全问题.还有可能导致存在需要被释放的资源得不到释放,引发内存泄露.所以用stop ...