感受
这次的三道题理解还不太好,下次不会的时候再复习吧。
530.二叉搜索树的最小绝对差
-
力扣链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
-
代码随想录视频讲解链接:https://www.bilibili.com/video/BV1DD4y11779
/**
530. 二叉搜索树的最小绝对差
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
提示:
树中节点的数目范围是 [2, 104]
0 <= Node.val <= 10^5
*/
class Solution {
TreeNode pre = null;
int ret = Integer.MAX_VALUE;//结果用ret记录,初值为Integer.MAX_VALUE
public int getMinimumDifference(TreeNode root) {
// 二叉搜索树:中序遍历,双指针
traversal(root);
return ret;
}
public void traversal(TreeNode root){
if(root == null){
return;
}
traversal(root.left);//左
// 中
if(pre != null){
ret = Math.min(ret, root.val - pre.val);
}
pre = root;
traversal(root.right);//右
}
}
501.二叉搜索树中的众数
-
力扣链接:https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
-
代码随想录视频讲解链接:https://www.bilibili.com/video/BV1fD4y117gp
/**
501. 二叉搜索树中的众数
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树
提示:
树中节点的数目在范围 [1, 104] 内
-10^5 <= Node.val <= 10^5
*/
class Solution {
ArrayList<Integer> retList;
int cnt;
int maxCount;
TreeNode pre;
public int[] findMode(TreeNode root) {
retList = new ArrayList<>(); //返回结果值
cnt = 0; //记录单个元素个数
maxCount = 0; //目前为止的最大元素频率
pre = null; //遍历BST
findMode1(root);
//把获取的retList转换成int[]类型
int[] ret = new int[retList.size()];
for(int i = 0; i < retList.size(); i++){
ret[i] = retList.get(i);
}
return ret;
}
//双指针、中序遍历
public void findMode1(TreeNode root){
if(root == null){
return;
}
findMode1(root.left);
if(pre == null || pre.val != root.val){
cnt = 1;
}else{
cnt += 1;
}
//更新retList
if(cnt == maxCount){
retList.add(root.val);
}else if(cnt > maxCount){
retList.clear();
retList.add(root.val);
maxCount = cnt;
}
pre = root;
findMode1(root.right);
}
}
236. 二叉树的最近公共祖先
-
力扣链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
-
代码随想录视频讲解链接:https://www.bilibili.com/video/BV1jd4y1B7E2
/**
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
提示:
树中节点数目在范围 [2, 10^5] 内。
-10^9 <= Node.val <= 10^9
所有 Node.val 互不相同 。
p != q
p 和 q 均存在于给定的二叉树中。
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//递归终止条件
if(root == null){
return null;
}
if(root == p || root == q){
return root;
}
//自底向上遍历--后序--回溯
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left == null && right == null){
return null;
}else if(left != null && right == null){
return left;
}else if(left == null && right != null){
return right;
}else{
return root;
}
}
}