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],

501. <wbr>Find <wbr>Mode <wbr>in <wbr>Binary <wbr>Search <wbr>Tree

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

 

Solution1://找出出现频率最高的元素

class Solution {

    Integer prev = null;

    int count = 1;

    int max = 0;

    public int[] findMode(TreeNode root) {

        if (root == null) return new int[0];

        List<Integer> list = new ArrayList<>();  //创建一个ArrayList,因为是动态大小的,所以方便数据添加。

        traverse(root, list);

        int[] res = new int[list.size()];

        for (int i = 0; i < list.size(); i++) res[i] = list.get(i);

        return res; 

    }

 

    private void traverse(TreeNode root, List list) {

         if (root == null) return;

         traverse(root.left, list);  

         if (prev != null) {  //在第一次使用traverse方法时,prev是null所以此判断语句不会运行,之后运行到此处                                           时,prev不是null所以会根据情况判断是否把count加一

             if (root.val == prev)

                 count ++;

             else 

                 count = 1;

         }

         if (count > max) { //如果此节点值的数量大于max,则把此节点加入ArrayList中(并删了之前的节点)

             max = count;

             list.clear();

             list.add(root.val);

         } else if (count == max) {

             list.add(root.val);

         }

         prev = root.val;  //最后才把节点的值赋给prev

         traverse(root.right, list);

    }

}

posted @   MarkLeeBYR  阅读(80)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示