leetcode 501. Find Mode in Binary Search Tree(找二叉搜索树中的众数)

本文介绍了一种在二叉搜索树中查找众数的高效算法,利用中序遍历的特点,避免了额外的空间使用,仅通过递归实现。算法首先进行中序遍历,若遇到重复节点则增加计数,否则重置计数。当计数超过最大计数时,清空结果列表并添加当前节点值;当计数等于最大计数时,将当前节点值添加到结果列表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

给出一棵二叉搜索数,输出它的众数,即出现次数最多的数,可能有重复元素,众数有多个时,可按任意顺序输出。

思路:
如果是数组中找相同元素出现的次数,最简单的方法是排序,然后按顺序遍历数组。
而二叉搜索树有一个特点,就是中序遍历的输出就是排序后的数组。
可以把中序遍历结果保存在一个数组中,然后查找每个元素出现的次数。
而follow up中指出可以不用额外的存储空间,
因为中序遍历是按从小到大的顺序的,所以相同的元素必然会连续访问。这时可以用一个TreeNode记录下前一个node,用一个count记录下当前元素出现的次数,maxCount记录下最多出现元素的次数。

如果前一个node为null或者前一个node的值不等于当前node的值,count就要重置为1,如果前一个node的值等于当前node值,则count++。
然后count与maxCount相比,如果和maxCount一样,那么直接把值添加进结果的list中,大于maxCount时就说明当前node的值是众数,要把之前list中的结果全部删除,再添加当前值。

//0ms
class Solution {
    TreeNode pre = null;
    int cnt = 0;
    int maxCnt = 0;
    
    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[]{};
        }
        ArrayList<Integer> list = new ArrayList<>();
        inOrder(root, list);
        
        int[] result = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        
        return result;
    }
    
    public void inOrder(TreeNode root, ArrayList<Integer> list) {
        if(root == null) {
            return;
        }
        
        inOrder(root.left, list);
        
        if(pre == null || pre.val != root.val) {
            cnt = 1;          
        } else {
            cnt ++;
        }
        if(cnt > maxCnt) {
            list.clear();
            list.add(root.val);
        } else if(cnt == maxCnt) {
            list.add(root.val);
        }
        
        pre = root;
        maxCnt = Math.max(cnt, maxCnt);
        
        inOrder(root.right, list);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值