BST的最小绝对差
同样也可以先变成数组, 然后比较数组的绝对差, 但是不是最优解
注意:
1. 这里用的是ArrayList集合不是数组, 所以遍历时要用list.get(i)
2.写的中序递归不需要return, 递归遍历怎么写, 这里就怎么写, 只不过需要在solution里return
3.判断list.size()小于二, 否则说明只有一个节点
class Solution {
ArrayList<Integer> list = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
//先中序遍历转换为数组
recur(root);
if(list.size() < 2){
return 0;
}
int res = Integer.MAX_VALUE;
for(int i = 1; i < list.size(); i++){
res = Math.min(res, list.get(i) - list.get(i-1));
}
return res;
}
private void recur(TreeNode root){
if(root == null){
return;
}
recur(root.left);
list.add(root.val);
recur(root.right);
}
}
和上一题一样, 可以定义pre node, 一边遍历一边比较
class Solution {
//定义一个节点用来比较
//定义一个最大值, 来收集最小值
TreeNode pre;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root == null){
return 0;
}
//左
getMinimumDifference(root.left);
//中, 条件是如果不等于null
if(pre != null){
//因为BST, 后一位肯定比前一位大, 所以顺序不重要
res = Math.min(res, root.val - pre.val);
}
//还是要记得移动节点
pre = root;
//右
getMinimumDifference(root.right);
return res;
}
}
二叉搜索树的众数
定义全局变量, 一个pre节点, 一个count记录单个次数, maxCount记录最大次数, 一个集合来收集众数
递归函数有两部分:
-
左中右, 中的时候要首先判断pre == cur, 如果相等的话count++
-
然后第二部分是来判断maxCount, 如果大的话就更新maxCount, 同时更新数组
然后在主方法里面把集合转变为数组
class Solution {
//定义全局变量, 一个集合收集元素, 一个count, 一个maxCount和一个pre节点
ArrayList<Integer> resList = new ArrayList<>();
int maxCount = 0;
int count = 0;
TreeNode pre = null;
public int[] findMode(TreeNode root) {
//傻逼,记得调用递归函数
recur(root);
//这个里面的话就把集合转变为数组就行了
int[] res = new int[resList.size()];
for(int i = 0; i< resList.size(); i++){
res[i] = resList.get(i);
}
return res;
}
//写递归方法
public void recur(TreeNode root){
if(root == null){
return;
}
//左
recur(root.left);
//中, 判断pre, 然后技术
//如果pre是null, 或者不相等的情况, count就等于1
if(pre == null || pre.val != root.val){
count = 1;
} else {
//别的情况, 也就是相等时, count++
count++;
}
//计完数之后, 来得到maxCount的值
if(count == maxCount){
resList.add(root.val);
} else if (count > maxCount){
//如果大于maxCount,说明找到最大值了
//这里有几步: 清楚原先的数, 然后把新的rootvalue加进来, 然后更新maxCount
resList.clear();
resList.add(root.val);
maxCount = count;
}
//搞完之后更新节点
pre = root;
//右
recur(root.right);
}
}
二叉树的最近公共祖先:
需要从下往上遍历, 找到最近的公共祖先, 所以需要后序遍历
递归三种情况
情况一: pq为孩子节点, 不为null, 所以就返回root
情况二:p为空, q不为空, 那么直接返回q
情况三:p不为空, q为空, 那么直接返回p
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//确定终止条件, 当越过叶子节点, 当指到p,q时吗都要return root
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 null;
}
if(left == null){
return right;
}
if(right == null){
return left;
} else {
return root;
}
}
}