501. Find Mode in Binary Search Tree

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

 

复制代码
private readonly Dictionary<int, int> dictionary = new Dictionary<int, int>();

        public int[] FindMode(TreeNode root)
        {
            Chuck(root);
            if (dictionary.Count > 0)
            {
                int max = dictionary.Max(x => x.Value);
                var array = dictionary.Where(x => x.Value == max).Select(x => x.Key).ToArray();
                return array;
            }
            else
            {
                return new int[0];
            }
        }

        private void Chuck(TreeNode node)
        {
            if (node == null)
            {
                return;
            }

            int val = node.val;
            if (dictionary.ContainsKey(val))
            {
                dictionary[val]++;
            }
            else
            {
                dictionary[val] = 1;
            }
            Chuck(node.left);
            Chuck(node.right);
        }
复制代码
Runtime: 272 ms, faster than 32.05% of C# online submissions for Find Mode in Binary Search Tree.
Memory Usage: 33.1 MB, less than 11.30% of C# online submissions forFind Mode in Binary Search Tree.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(184)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-06-01 Define class with itself as generic implementation. Why/how does this work?
2016-06-01 Task.ConfigureAwait
2015-06-01 新建并保存一个空的Excel
2015-06-01 创建了对嵌入的互操作程序集间接引用,无法嵌入互操作类型
2015-06-01 演练:Office 编程(C# 和 Visual Basic)
2015-06-01 C#6.0 VS2015
2015-06-01 23种设计模式
点击右上角即可分享
微信分享提示