leetcode-501:二叉搜索树中的众数

简介: leetcode-501:二叉搜索树中的众数

题目

题目链接

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

  • 结点左子树中所含结点的值小于等于当前结点的值
  • 结点右子树中所含结点的值大于等于当前结点的值
  • 左子树和右子树都是二叉搜索树

例如:

给定 BST [1,null,2,2],

1
    \
     2
    /
   2

返回[2].

解题

方法一:中序遍历+暴力统计

先中序遍历,然后用dict统计每个元素的值出现频率,然后排序把高频出现的放在前面,最后把高频出现的值给取出来

python解法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findMode(self, root: TreeNode) -> List[int]:
        #中序遍历
        if not root:
            return []
        stack = []
        res = []
        cur = root
        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        #统计频率
        hush = {}
        for num in res:
            hush[num]=hush.get(num,0)+1
        #排序(频率高的放前面)
        tmp = []
        for key,freq in hush.items():
            tmp.append((freq,key))
        tmp.sort(reverse=True)
        # 取出频率高的
        res = []
        prev = None
        for freq,key in tmp:
            if not prev or prev==freq:
                res.append(key)
                prev = freq
        return res

c++解法

按出现频率排序,这题用到 直接排序的方法,也就是sort,并且自定义排序函数

leetcode-347:前 K 个高频元素此题中使用的是堆排序。

要能够掌握直接排序和堆排序.

class Solution {
public:
    bool static cmp(const pair<int,int>& a,const pair<int,int>& b){
        return a.second>b.second;
    }
    vector<int> findMode(TreeNode* root) {
        stack<TreeNode*> stack;
        TreeNode* cur=root;
        unordered_map<int,int> map;
        while(!stack.empty()||cur){
            while(cur){
                stack.push(cur);
                cur=cur->left;
            }
            cur=stack.top();
            stack.pop();
            map[cur->val]++;
            cur=cur->right;
        }
        vector<pair<int,int>> vec(map.begin(),map.end());
        sort(vec.begin(),vec.end(),cmp);
        vector<int> res;
        res.push_back(vec[0].first);
        for(int i=1;i<vec.size();i++){
            if(vec[i].second==vec[0].second) res.push_back(vec[i].first);
            else break;
        }
        return res;
    }
};

java解法

class Solution {
    public int[] findMode(TreeNode root) {
        if(root==null) return new int[]{};
        Map<Integer,Integer> mp=new HashMap<>();
        //遍历树
        Queue<TreeNode> q=new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            TreeNode cur=q.poll();
            mp.put(cur.val,mp.getOrDefault(cur.val,0)+1);
            if(cur.left!=null){
                q.add(cur.left);
            }
            if(cur.right!=null){
                q.add(cur.right);
            }
        }
        //找到高频元素
        //创建大顶堆
        PriorityQueue<Integer> pq=new PriorityQueue<>(new Comparator<Integer>(){
            public int compare(Integer a,Integer b){
                if(mp.get(a)>mp.get(b)) return -1;
                else return 1;
            }
        });
        for(Integer key:mp.keySet()){
            pq.add(key);
        }
        List<Integer> res=new ArrayList<>();
        res.add(pq.poll());
        int k=mp.get(res.get(0));
        while(!pq.isEmpty()&&mp.get(pq.peek())==k){
            res.add(pq.poll());
        }
        int[] ans=new int[res.size()];
        for(int i=0;i<res.size();i++){
            ans[i]=res.get(i);
        }
        return ans;
    }
}


相关文章
|
4月前
|
机器学习/深度学习 存储 算法
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
|
2月前
|
Python
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
28 4
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
|
2月前
|
Python
【Leetcode刷题Python】96. 不同的二叉搜索树
LeetCode 96题 "不同的二叉搜索树" 的Python解决方案,使用动态规划算法计算由1至n互不相同节点值组成的二叉搜索树的种数。
19 3
【Leetcode刷题Python】96. 不同的二叉搜索树
|
2月前
|
算法
LeetCode第96题不同的二叉搜索树
文章介绍了LeetCode第96题"不同的二叉搜索树"的解法,利用动态规划的思想和递推公式,通过计算以任意节点为根的不同二叉搜索树的数量,解决了该问题。
LeetCode第96题不同的二叉搜索树
|
2月前
|
算法 Python
【Leetcode刷题Python】剑指 Offer 33. 二叉搜索树的后序遍历序列
本文提供了一种Python算法,用以判断给定整数数组是否为某二叉搜索树的后序遍历结果,通过识别根节点并递归验证左右子树的值是否满足二叉搜索树的性质。
17 3
|
2月前
|
Python
【Leetcode刷题Python】538. 把二叉搜索树转换为累加树
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
19 3
|
2月前
|
Python
【Leetcode刷题Python】108. 将有序数组转换为二叉搜索树
LeetCode上108号问题"将有序数组转换为二叉搜索树"的Python实现,通过递归选取数组中间值作为根节点,构建高度平衡的二叉搜索树。
23 2
|
4月前
|
存储 算法 数据可视化
LeetCode 题目 96:从动态规划、递归到卡塔兰数实现不同的二叉搜索树
LeetCode 题目 96:从动态规划、递归到卡塔兰数实现不同的二叉搜索树
|
5月前
|
存储
【LeetCode】剑指 Offer 54. 二叉搜索树的第k大节点
【LeetCode】剑指 Offer 54. 二叉搜索树的第k大节点
40 1
|
4月前
|
存储 算法 数据挖掘
力扣173题:二叉搜索树迭代器(含模拟面试)
力扣173题:二叉搜索树迭代器(含模拟面试)