代码随想录算法训练营第二十三天 |二叉搜索树的最小绝对差、二叉搜索树中的众数 、二叉树的最近公共祖先
好几天没打卡了,先补全打卡,大概是忙完了现在。🫥🫥🫥
二叉搜索树的最小绝对差link
题目:给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
class Solution {
List<Integer> list = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
traverse(root);
return getMin();
}
//递归
//中序遍历
public void traverse(TreeNode root) {
if (root == null)
return;
traverse(root.left);
list.add(root.val);
traverse(root.right);
}
public int getMin() {
int min = Integer.MAX_VALUE;
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
int temp = Math.abs(list.get(i) - list.get(j));
min = Math.min(temp, min);
}
}
return min;
}
}
二叉搜索树中的众数 link
题目:给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树。
class Solution {
HashMap<Integer, Integer> map = new HashMap<>();// key存放元素,value存放次数
List<Integer> ans = new ArrayList<>();
Set<Integer> set = new HashSet<>();
public int[] findMode(TreeNode root) {
traverse(root);
return getCount();
}
// 递归
// 中序遍历
public void traverse(TreeNode root) {
if (root == null)
return;
traverse(root.left);
if (map.get(root.val) == null) {
map.put(root.val, 1);
} else {
map.put(root.val, map.get(root.val) + 1);
}
traverse(root.right);
}
public int[] getCount() {
int max = -1;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
max = Math.max(max, entry.getValue());
}
// 确保至少有一个众数
if (max == -1) {
// 你可以根据需求决定如何处理这种情况,比如返回一个空数组或抛出一个异常
return new int[0]; // 假设我们返回一个空数组
}
// 将众数添加到列表中,然后转换为数组
List<Integer> modeList = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == max) {
modeList.add(entry.getKey());
}
}
// 将列表转换为数组并返回
return modeList.stream().mapToInt(Integer::intValue).toArray();
}
}
/*
在Java 8及以后的版本中,Stream API 提供了一种声明式的方式来处理集合数据。对于List<Integer>,你可以使用stream()方法将其转换为一个Stream<Integer>,然后使用mapToInt方法将这个Stream<Integer>转换为一个特殊的IntStream,该流专门用于处理原始int类型的数据。
*/
二叉树的最近公共祖先link
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
视频推荐:link
class Solution {
//递归
//后序遍历
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//结束条件
if (root == null)
return null;
if (root == p || root == q)
return root;
//左
root.left = lowestCommonAncestor(root.left, p, q);
//右
root.right = lowestCommonAncestor(root.right, p, q);
//中
if (root.left != null && root.right != null)
return root;
if (root.left != null && root.right == null)
return root.left;
else if (root.left == null && root.right != null)
return root.right;
else
return null;
}
}
希望对您有帮助。