530.二叉搜索树的最小绝对差
题目描述:给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
思路:这题可以直接中序遍历转成数组,但是需要额外的数组空间。可以直接在原地进行比较,不过做差需要在遍历的时间记录前面的节点。这里的技巧就是设一个全局的变量pre来记录。
class Solution {
int res = Integer.MAX_VALUE;
TreeNode pre = new TreeNode(-1);
public int getMinimumDifference(TreeNode root) {
// 中序遍历有序,需要记录差值
inOrder(root);
return res;
}
public void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
if(pre.val >= 0){
res = Math.min(res,root.val - pre.val);
}
pre = root;
inOrder(root.right);
}
}
501.二叉搜索树中的众数
题目描述:给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
思路:和上一题一致,不过在处理众数的时候,需要记录每个值他的count为多少。并且当最大值更新时,需要清除之前的结果。
class Solution {
List<Integer> list = new LinkedList<>();
int count = 0;
int maxcount = 0;
TreeNode pre = null;
public int[] findMode(TreeNode root) {
inOrder(root);
int[] res = new int[list.size()];
for(int i = 0;i < list.size();i++){
res[i] = list.get(i);
}
return res;
}
public void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
// 处理计数
if(pre == null){
count = 1;
}else if(pre.val == root.val){
count++;
}else{
count = 1; //不一样,重制
}
pre = root;
// 每遍历一遍开始处理count
if(count == maxcount){
list.add(root.val);
}
if(count > maxcount){
maxcount = count;
list.clear(); // 关键是让之前的结果集清空
list.add(root.val);
}
inOrder(root.right);
}
}
236. 二叉树的最近公共祖先
题目描述:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
思路:这题的代码随想录的部分值得反复回顾。有几个细节,首先要知道最近公共祖先,必须先看左右子树,然后通过左右子树的值,再去比较。通过这个点,可以确定题目应该采用后序遍历,并且在递归的时候,必须要有返回值,然后才可以利用返回值进行比较。
回到题目本身,找最近公共祖先,其实就是要找到这两个节点就可以了,两个节点的情况分别对应3种,1种两边,2种自身。递归的中止条件就是找到自身的就可以,作为返回值给上一层进行判断。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 递归中止条件,找到p或者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 root;
if(left == null && right != null) return right;
if(left != null && right == null) return left;
return null;
}
}