530.二叉搜索树的最小绝对差
-
题目链接:代码随想录
-
解题思路一:
转化为有序数组求
二叉搜索树中序遍历的结果,就是一个有序数组,这时再求两个节点的差就好求了
public int getMinimumDifference(TreeNode root) {
ArrayList<Integer> arr = new ArrayList<>();
traversal(root, arr);
int result = Integer.MAX_VALUE;
for (int i = 1; i < arr.size(); i++) {
result = Math.min(result, Math.abs(arr.get(i) - arr.get(i - 1)));
}
return result;
}
public void traversal(TreeNode root,ArrayList<Integer> arr){
if(root == null){
return;
}
traversal(root.left, arr);
arr.add(root.val);
traversal(root.right, arr);
}
-
解题思路二:(双指针)
在遍历二叉树的过程中,就比较好了差值
这时需要记录当前节点和前一个节点这里要注意前一个节点指针的取法
public int result;
public TreeNode pre;//前一个节点
public int getMinimumDifference(TreeNode root) {
result = Integer.MAX_VALUE;
traversal(root);
return result;
}
public void traversal(TreeNode root){
if(root == null){
return;
}
traversal(root.left);//左
if(pre != null){
result = Math.min(result, root.val - pre.val);
}
pre = root;//pre指向root遍历的前一个节点,可以想root遍历到最底下返回的时候才会这样
traversal(root.right);
}
501.二叉搜索树中的众数 ⭐️
题目链接:代码随想录
-
①如果不是二叉排序树的做法:
①把整棵树都遍历一遍放进一个数组②用map集合统计出现次数②是二叉排序树的做法:
设置一个动态数组,根据maxCount和count值比较实时更新
public class Solution1 {
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;
}
private void traversal(TreeNode root) {
if(root == null){
return;
}
traversal(root.left);
//记录出现次数
if(pre == null || pre.val != root.val){//两种次数为1的情况
count = 1;
}else{
count++;//相等的情况
}
//出现大于最大次数的情况,更新接受数组
if(count > maxCount){
resList.clear();
resList.add(root.val);
maxCount = count;
}else if(count == maxCount){
resList.add(root.val);
}
pre = root;//前一个指针
traversal(root.right);
}
}
236. 二叉树的最近公共祖先⭐️
题目链接:代码随想录
- 解题思路:
① root用来接收返回值,返回最近公共祖先
② 关键点:
一层一层的返回root,返回到最后一层返回的root即为最近的公共祖先
如何判断返回的root情况,要采取后序遍历,得到两个节点的情况后才做出决定
③ 归纳:
1. 求最小公共祖先,需要从底向上遍历,那么二叉树,只能通过后序遍历(即:回溯)实现从底向上的遍历方式。
2. 在回溯的过程中,必然要遍历整棵二叉树,即使已经找到结果了,依然要把其他节点遍历完,因为要使用递归函数的返回值(也就是代码中的left和right)做逻辑判断。
3. 要理解如果返回值left为空,right不为空为什么要返回right,为什么可以用返回right传给上一层结果。
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;
}
if(left == null && right != null){
return right;
}
if(left != null && right == null){
return left;
}
//返回当前节点
if(left != null && right != null){
return root;
}
return root;
}