一、算法题
530.二叉搜索树的最小绝对差
class Solution {
int res=Integer.MAX_VALUE;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
//二叉搜索树,中序遍历
if(root==null){
return 0;
}
minnum(root);
return res;
}
public void minnum(TreeNode root){
if(root==null){
return;
}
//左
minnum(root.left);
//中
if(pre!=null){
res=Math.min(res, root.val-pre.val);
}
pre=root;
//右
minnum(root.right);
}
}
- 双指针
- pre用于保存上一个节点,因为对二叉搜索树进行中序遍历,节点的值都是有序的
- 这个判断的意义是,一开始pre初始化时是等于null的,所以第一次执行到这个语句的时候,也是刚刚找到按中序遍历遍历到的第一个结点(最小的那个结点),因为pre的作用是用来保存上一个结点的,但是这第一个结点没有上一个结点,所以加了这个判断条件。
- 也就默认第一个结点不执行该语句,后面的每个结点都要进行历史最小差值res与当前节点和上一个结点的差值的比较。
if(pre!=null){ res=Math.min(res, root.val-pre.val); }
501.二叉搜索树中的众数
class Solution {
List<Integer> res = new ArrayList<Integer>();//记录出现过最多次的元素
int max;//最大出现次数
int count;//出现次数
TreeNode pre;
public int[] findMode(TreeNode root) {
find(root);
//把列表转为数组
int [] result=new int[res.size()];
for (int i = 0; i < res.size(); i++) {
result[i]=res.get(i);
}
return result;
}
public void find(TreeNode root){
if(root==null){
return;
}
//左
find(root.left);
//中
//计数
//是第一个元素或前后元素不相等
if(pre==null||pre.val!=root.val){
//重新计数
count=1;
}
else{
//pre!=null且pre.val==root.val,即元素值相同
count++;
}
//更新最高频率
//出现个更高次数的元素,此时清空res然后把新元素加进去并修改max
if(count>max){
res.clear();
res.add(root.val);
max=count;
}else if(count==max){
//此时两个元素的出现次数相同,那就把新元素直接加进来
res.add(root.val);
}
pre=root;
//右
find(root.right);
}
}
- 因为是二叉搜索树,所以如果有相同的元素它们会连续出现
- 双指针
236. 二叉树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//递归结束条件
if(root==null){
return null;
}
//后序遍历
TreeNode left=lowestCommonAncestor(root.left, p, q);
TreeNode right=lowestCommonAncestor(root.right, p, q);
if(root==p || root==q){
return root;
}
if(left==null&&right==null){
//只有找到了祖先返回值才不是null而是祖先节点的值
return null;
}
else if(left==null&&right!=null){
return right;
}
else if(left!=null&&right==null){
return left;
}
//左右节点都找到了那个祖先节点
else{
return root;
}
}
}
- 情况一:如果找到一个节点,发现左子树出现结点p,右子树出现节点q,或者左子树出现结点q,右子树出现节点p,那么该节点就是节点p和q的最近公共祖先
- 情况二:节点本身p(q),它拥有一个子孙节点q(p)