博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
501. Find Mode in Binary Search Tree - Easy
阅读量:6679 次
发布时间:2019-06-25

本文共 1971 字,大约阅读时间需要 6 分钟。

Given a binary search tree (BST) with duplicates, find all the  (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).

 

M1: using extra space

traverse的时候,用hashmap存每个节点出现的次数

time: O(n), space: O(n)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    int max = 0;        public int[] findMode(TreeNode root) {        if(root == null) {            return new int[] {};        }        Map
map = new HashMap<>(); traverse(root, map); List
tmp = new ArrayList<>(); for(Map.Entry
entry : map.entrySet()) { if(entry.getValue() == max) { tmp.add(entry.getKey()); } } int[] res = new int[tmp.size()]; for(int i = 0; i < tmp.size(); i++) { res[i] = tmp.get(i); } return res; } public void traverse(TreeNode root, Map
map) { if(root == null) { return; } map.put(root.val, map.getOrDefault(root.val, 0) + 1); max = Math.max(max, map.get(root.val)); traverse(root.left, map); traverse(root.right, map); }}

 

M2: optimized, not using extra space

 

转载于:https://www.cnblogs.com/fatttcat/p/10200168.html

你可能感兴趣的文章
jQuery Ajax遍历表格,填充数据,将表格中的数据一条一条拼成Jason数组
查看>>
Redis为什么这么快
查看>>
js获取宽度设置thickbox百分比
查看>>
检测输入框字数的变化 注意onpropertychange oninput onchange onkeyup区别
查看>>
arm_GPIO_简单编程例题
查看>>
codves1282 约瑟夫问题 链表 会 T
查看>>
接口调用的跨域问题
查看>>
关于乌班图18.04安装mysql不提示设置密码解决方案
查看>>
php数据类型以及运算
查看>>
npm命令
查看>>
关于实现(大)系统的一些小体会
查看>>
如何使用github创建仓库并且与本地连接
查看>>
除法(简单枚举)
查看>>
System.Web.Caching
查看>>
linux常用命令 2
查看>>
jquery中prop和attr的区别
查看>>
2016-2017 ACM-ICPC Pacific Northwest Regional Contest (Div. 1) Problem K Tournament Wins
查看>>
台州学院we are without brain 训练 计算几何
查看>>
Webpack 代码分离
查看>>
ssh下:系统初始化实现ServletContextListener接口时,获取spring中数据层对象无效的问题...
查看>>