赞
踩
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
先遍历二叉树,把每个出现的数字,和数字的个数存放到map中,如果先遍历一次map的所有value,找出最大的出现次数max,和最大次数的相同个数count,创建count大的数组,再遍历map的所有key,如果map.get(key)等于最大值,则把key放到数组中,最后返回数组。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { //记录每个出现的数字,和数字的个数 private Map<Integer, Integer> map = new HashMap<>(); public int[] findMode(TreeNode root) { //遍历二叉树填充map func(root); //找出数字最大的个数数 int max = 0; //记录相同的值的个数,以便后面创建数组的个数 int count = 0; for (Integer value : map.values()) { if (value > max) { max = value; count = 1; } else if (value == max) count++; } int[] result = new int[count]; //此时的count代表数组的存放下标 count = 0; for (Integer key : map.keySet()) { if (map.get(key) == max) result[count++] = key; } return result; } //递归遍历 private void func(TreeNode tree) { //出口 if (tree == null) return; map.put(tree.val, map.containsKey(tree.val) ? map.get(tree.val) + 1 : 1); //遍历左子树 func(tree.left); //遍历右子树 func(tree.right); } }
自己写的,没去看题解,效率不太好。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。