【LeetCode每日一题】[简单]501. 二叉搜索树中的众数
501. 二叉搜索树中的众数
题目来源
算法思想:树,中序遍历
题目:
java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//1.中序遍历,li从小到大的数组;
//2.找到众数重复频率;
//3.遍历li数组,记录众数
class Solution {
public int[] findMode(TreeNode root) {
if(root == null){
return new int[0];
}
List<Integer> li = new ArrayList<Integer>();//得到有序数组(从小到大)
List<Integer> res = new ArrayList<Integer>();//最后返回的答案int[]
dfs(root, li);//中序遍历,得到数组
int[] dp = new int[li.size()];//用来统计相同数值
for (int i = 0; i < dp.length; i++) {
dp[i] = 1;
}
int count = 1;//众数数量,重复的数值数量
for (int i = 1; i < dp.length; i++) {
//Integer(-128 ~ 127)以外的数值要用intValue进行比较
if((li.get(i).intValue() == li.get(i-1).intValue())) {
dp[i] = dp[i-1] + 1;
}
if(dp[i] > count) {
count = dp[i];
}
}
//记录众数
for (int i = 0; i < dp.length; i++) {
if(dp[i] == count) {
res.add(li.get(i));
}
}
//list转成int[]
int[] answer = new int[res.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = res.get(i);
}
return answer;
}
//二叉搜索树中序遍历
public void dfs(TreeNode root, List<Integer> list) {
if(root == null) {
return;
}
dfs(root.left, list);
list.add(root.val);
dfs(root.right, list);
}
}
PS:Integer数值比较
链接.
1、数值类型,值在-128 ~ 127的之间的数值对象,在Integer或者Long…的内部类中IntegerCache中。没有实质性创建对象或者说对象都内部类的cache[]数组中,使用==没有问题返回true,因为是同一对象。
2、数值在-128 ~ 127范围之外的数值类型,都重新创建了对象。再使用“==”,就返回false了。
3、new Integer(0);如果这样写,同样创建了对象,及时值在-128 ~ 127的之间。使用“==”同样返回false;
Integer a = 100;
Integer b = 100;
if (a == b) {
// true
System.out.println(true);
}
else{
System.out.println(false);
}
a = 100000;
b = 100000;
if (a == b) {
// false
System.out.println(true);
}
else{
System.out.println(false);
}
//使用equals
if (a.equals(b)) {
// true
System.out.println(true);
}
else {
System.out.println(false);
}