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

来源:互联网 发布:淘宝玻璃钢化粪罐 编辑:程序博客网 时间:2024/06/08 09:22

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