501二叉搜索树中的众数

题目描述

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

假定 BST 有如下定义:

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

例如:
给定 BST [1,null,2,2],返回[2].

提示:如果众数超过1个,不需考虑输出顺序

思路分析

BST中序遍历是升序序列,逐个比对当前结点(root)值与前驱结点(pre)值。更新当前节点值出现次数(curTimes)及最大出现次数(maxTimes)。

若curTimes=maxTimes,将root.val添加到list中;若curTimes>maxTimes,清空list,再添加,并更新maxTimes为curTimes。

代码实现

    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        List<Integer> arrayList = new ArrayList<>();
        process(root, arrayList);
        int[] ret = new int[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            ret[i] = arrayList.get(i);
        }
        return ret;
    }

    int curTimes=1;
    int maxTimes=0;
    TreeNode pre=null;

    public void process(TreeNode root, List<Integer> ret) {
        if (root == null) {
            return;
        }
        process(root.left, ret);

        if (pre != null) {
            curTimes = root.val == pre.val ? curTimes + 1 : 1;
        }
        if (maxTimes == curTimes) {
            ret.add(root.val);
        } else if (curTimes > maxTimes) {
            maxTimes = curTimes;
            ret.clear();
            ret.add(root.val);
        }
        pre = root;
        process(root.right, ret);
    }

发布了158 篇原创文章 · 获赞 12 · 访问量 5551

猜你喜欢

转载自blog.csdn.net/qq_34761012/article/details/104696953