530.二叉搜索树的最小绝对差
public class MinimumAbsoluteDifferenceinBST {
//递归-双指针
int result = Integer.MAX_VALUE;
TreeNode pre;// 记录上一个遍历的结点
public int getMinimumDifference(TreeNode root) {
if(root == null) return 0;
traversal(root);
return result;
}
public void traversal(TreeNode cur){
if (cur == null) return;
//左
traversal(cur.left);
//中
if(pre !=null){
result = Math.min(result, cur.val - pre.val);
}
pre = cur;//pre一直跟着cur
//右
traversal(cur.right);
}
}
501.二叉搜索树中的众数
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class FindModeinBinarySearchTree {
public int[] findMode(TreeNode root) {
//暴力法
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
if(root == null) return list.stream().mapToInt(Integer:: intValue).toArray();
//1.遍历二叉树,每个元素出现的频率是map统计,把频率排序,把map转变list后再排序
// 获得频率 Map
searchBST(root, map);
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
.sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
.collect(Collectors.toList());
list.add(mapList.get(0).getKey());
//2.在list中求众数
// 把频率最高的加入 list
for(int i = 1; i < mapList.size(); i++){
if(mapList.get(i).getValue() == mapList.get(i - 1).getValue()){
list.add(mapList.get(i).getKey());
}else {
break;
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
void searchBST(TreeNode curr, Map<Integer, Integer> map){
if(curr == null) return;
map.put(curr.val, map.getOrDefault(curr.val,0) + 1);
searchBST(curr.left, map);
searchBST(curr.right, map);
}
}
//方法二:双指针思路
//二叉搜索树就是用中序遍历-不使用额外空间,利用二叉搜索树特性
ArrayList<Integer> resList;
int maxCount;
int count;
TreeNode pre;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
traversal(root);
int[] res = new int[resList.size()];
for(int i = 0; i < resList.size(); i++){
res[i] = resList.get(i);
}
return res;
}
public void traversal(TreeNode cur){
if(cur == null) return;
//左
traversal(cur.left);
//中-逻辑
//1.计数
if(pre == null || cur.val!= pre.val){
count = 1;
}else { //else if(cur.val == pre.val)
count++;
}
// 更新结果以及maxCount
if(count > maxCount){
resList.clear();
resList.add(cur.val);
maxCount = count;
}else if(count == maxCount){
resList.add(cur.val);
}
pre = cur;
//右
traversal(cur.right);
}
236. 二叉树的最近公共祖先
public class LowestCommonAncestorofaBinaryTree {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//处理顺序可以从下往上-回溯
//回溯一定要后序(左右中)
//1. 递归结束条件
if(root == null) return null;
if( root == p || root == q) return root;
//2. 后序遍历
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null)return root;
else if(left == null && right != null) return right;
else if(left != null && right == null) return left;
else return null;
}
}