代码随想录算法刷题训练营day21:LeetCode(501)二叉搜索树中的众数、LeetCode(530)二叉搜索树的最小绝对差
LeetCode(501)二叉搜索树中的众数
题目
代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int[] findMode(TreeNode root) {
//定义一个集合存储数据
List<Integer> dateTree=new ArrayList<>();
getDateTree(root,dateTree);
Map<Integer,Integer> mapTreedate=new HashMap<>();
for(int i=0;i<dateTree.size();i++){
int tempDate=dateTree.get(i);
if(mapTreedate.containsKey(tempDate)){
mapTreedate.put(tempDate,mapTreedate.get(tempDate)+1);
}else{
mapTreedate.put(tempDate,1);
}
}
//用Map集合存储数据
int count=0;
for(Map.Entry<Integer,Integer> entry:mapTreedate.entrySet()){
int key=entry.getKey();
int countValue=entry.getValue();
if(countValue>=count){
count=countValue;
}
}
List<Integer> resultDate=new ArrayList<>();
for(Map.Entry<Integer,Integer> entry:mapTreedate.entrySet()){
if(entry.getValue().equals(count)){
resultDate.add(entry.getKey());
}
}
int[] result=new int[resultDate.size()];
for(int i=0;i<resultDate.size();i++){
result[i]=resultDate.get(i);
}
return result;
}
//遍历树
public void getDateTree(TreeNode root,List<Integer> dateTree){
if(root==null){
return;
}
dateTree.add(root.val);
getDateTree(root.left, dateTree);
getDateTree(root.right, dateTree);
}
}
LeetCode(530)二叉搜索树的最小绝对差
题目
代码
import java.util.ArrayList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
List<Integer> dateTree=new ArrayList<>();
getTreeDate(root,dateTree);
int minDate=Math.abs(dateTree.get(0)-dateTree.get(1));
for (int i = 0; i < dateTree.size(); i++) {
for(int j=i+1;j<dateTree.size();j++){
int tempDate=Math.abs(dateTree.get(i)-dateTree.get(j));
if(tempDate<minDate){
minDate=tempDate;
}
}
}
return minDate;
}
public void getTreeDate(TreeNode root,List<Integer> dateTree){
if(root==null){
return;
}
dateTree.add(root.val);//中序
getTreeDate(root.left, dateTree);
getTreeDate(root.right, dateTree);
}
}