LeetCode-501. Find Mode in Binary Search Tree(Java)

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

------------------------------------------------------------------------------------------------------------------------------------

题意

从一个二叉搜索树中找到出现最频繁的元素,即出现次数最多的元素。

思路

采用三个遍历方式之一;因为要记录相同元素出现的次数,所以需要记录上一个节点用来判断,如果上一个节点与当前节点相同,

则出现次数加1,否则,出现次数重置,当前节点赋值给上一个节点;同时记录大于等于出现最大次数的元素,所以需要一个数组,

然后需要一个计数器,当如果上一个节点与当前节点不相同时并且当前节点出现次数大于或等于最大出现次数,把该节点值添加到数组,

并且该计数器加1。大致思路如此

代码

public class Solution {
    public int[] findMode(TreeNode root) {
        inorder(root);
        modes = new int[modeCount];
        modeCount = 0;
        currCount = 0;
        inorder(root);
        return modes;
    }
    //记录元素值
    private int currVal;
    //记录相同元素出现次数
    private int currCount = 0;
    //记录出现的最大次数
    private int maxCount = 0;
    //作为modes数组的下标,记录出现相同最大次数的元素个数
    private int modeCount = 0;
    
    private int[] modes;
    private void handleValue(int val) {
        if (val != currVal) {
            currVal = val;
            currCount = 0;
        }
        currCount++;
        if (currCount > maxCount) {
            maxCount = currCount;
            modeCount = 1;
        } else if (currCount == maxCount) {
            if (modes != null)
                modes[modeCount] = currVal;
            modeCount++;
        }
    }
    
    private void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        handleValue(root.val);
        inorder(root.right);
    }
}

参考链接:https://discuss.leetcode.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值