作者: 负雪明烛
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)的更多相关文章

  1. 【LeetCode】669. Trim a Binary Search Tree 解题报告(Python)

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

  2. 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 ...

  3. 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 ...

  4. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

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

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

  6. 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  ...

  7. 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 ...

  8. LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告

    https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest ...

  9. 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...

随机推荐

  1. 一款真正可以拿的出手的本土嵌入式RTOS-SylixOS

    由 winniewei 提交于 周四, 12/20/2018 作者:张国斌 在参加工信部人才交流中心和南京浦口区开发区管委会联合举办的第三届集成电路产业紧缺人才创新发展高级研修班暨产业促进交流会期间, ...

  2. 构建LNMP+WordPress

    1. 安装LNMP环境 首先修改主机名 [root@samba ~]# hostnamectl set-hostname lnmp[root@lnmp lnmp1.6-full]# hostnamec ...

  3. JVM结构详解

    JVM 结构详解 JVM 结构图 程序计数器(PC 寄存器) 程序计数器的定义 程序计数器是一块较小的内存空间,是当前线程正在执行的那条字节码指令的地址.若当前线程正在执行的是一个本地方法,那么此时程 ...

  4. day02 MySQL基本操作

    day02 MySQL基本操作 昨日内容回顾 数据库演变史 1.纯文件阶段 2.目录规范 3.单机游戏 4.联网游戏 # 数据库就是一款帮助我们管理数据的程序 软件开发架构及数据库本质 cs架构与bs ...

  5. 零基础学习java------38---------spring中关于通知类型的补充,springmvc,springmvc入门程序,访问保护资源,参数的绑定(简单数据类型,POJO,包装类),返回数据类型,三大组件,注解

    一. 通知类型 spring aop通知(advice)分成五类: (1)前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. (2)正常返回通知 ...

  6. Oracle中创建DB LINK

    当用户要跨本地数据库,访问另外一个数据库表中的数据时,本地数据库中必须创建了远程数据库的dblink,通过dblink本地数据库可以像访问本地数据库一样访问远程数据库表中的数据.下面讲介绍如何在本地数 ...

  7. springboot热部署与监控

    一.热部署 添加依赖+Ctrl+F9 <dependency> <groupId>org.springframework.boot</groupId> <ar ...

  8. MyBatis(2):CRUD操作

    编写接口 import com.shandx.pojo.User; import java.util.List; public interface UserMapper { <span clas ...

  9. Java Log4j 配置文件

    ### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.lo ...

  10. Mybatis-Plus默认主键策略导致自动生成19位长度主键id的坑

    原创/朱季谦 某天检查一位离职同事写的代码,发现其对应表虽然设置了AUTO_INCREMENT自增,但页面新增功能生成的数据主键id很诡异,长度达到了19位,且不是从1开始递增的-- 我检查了一下,发 ...