代码随想录刷题Day21 | 530.二叉搜索树的最小绝对差 | 501.二叉搜索树中的众数 | 236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
题目:
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
思路:
搜索二叉树的中序遍历是一个有序数组!!!,利用这个特性,我们使用中序遍历,记录当前节点和前一个节点,就不需要使用额外的空间找到最小绝对差了。
代码:
class Solution {
int min = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
inorder(root);
return min;
}
public void inorder(TreeNode root){
if(root.left != null){
inorder(root.left);
}
if(pre != null && root.val - pre.val < min){
min = root.val - pre.val;
}
pre = root;
if(root.right != null){
inorder(root.right);
}
}
}
501.二叉搜索树中的众数
题目:
给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
思路:
前序遍历搜索二叉树得到的是一个有序数组,我们只需要记录下当前数字已经出现的频率,如果大于等于最大频率,添加进数组,大于最大频率,清空数组再添加进数组。
代码:
class Solution {
int maxfre = 0, fre = 0;
ArrayList<Integer> result = new ArrayList<>();
TreeNode pre = null;
public int[] findMode(TreeNode root) {
inorder(root);
return result.stream().mapToInt(Integer::intValue).toArray();
}
public void inorder(TreeNode cur){
if(cur.left != null){
inorder(cur.left);
}
if(pre != null && cur.val == pre.val){
fre++;
}else{
fre = 1;
}
if(fre > maxfre){
maxfre = fre;
result.clear();
result.add(cur.val);
}else if(fre == maxfre){
result.add(cur.val);
}
pre = cur;
if(cur.right != null){
inorder(cur.right);
}
}
}
236. 二叉树的最近公共祖先
题目:
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路:
采用回溯的思想,从底向上找。
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || 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 left;
else if(left == null && right != null) return right;
else if(left == null && right == null) return null;
else return root;
}
}