今日任务:
1 .二叉搜索树的最小绝对值
2.二叉搜索树中的众数
3.二叉树的最近公共祖先
1 .二叉搜索树的最小绝对值
思路:这道题老套路使用中序遍历,然后双指针一起移动,比对res的大小。
class Solution {
private int res = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root == null) return;
//左
dfs(root.left);
//中
if(pre != null){
res = Math.min(res,root.val - pre.val);
}
pre = root;
//右
dfs(root.right);
}
}
2.二叉搜索树中的众数
思路:一样的思路,运用双指针遍历一遍搜索二叉树,同时要保存当时的最大频率,因为答案需要的是一个数组,众数可能不唯一,所以要判断每个数的频率:
如果 频率count 等于 maxCount(最大频率),当然要把这个元素加入到结果集中。
如果频率count 大于 maxCount的时候,不仅要更新maxCount,而且要清空结果集(以下代码为result数组),因为结果集之前的元素都失效了。
class Solution {
private List<Integer> res = new ArrayList<>();
private TreeNode pre = null;
private int count = 0;
private int maxCount = 0;
public int[] findMode(TreeNode root) {
dfs(root);
int ans[] = new int[res.size()];
for (int i = 0; i < ans.length; i++) {
ans[i] = res.get(i);
}
return ans;
}
public void dfs(TreeNode cur){
if(cur == null) return;
//左
dfs(cur.left);
//中
if(pre == null) count = 1;
else if(pre.val == cur.val) count++;
else count = 1;
if(count > maxCount){
res.clear();
res.add(cur.val);
maxCount = count;
} else if (count == maxCount) {
res.add(cur.val);
}
pre = cur;
dfs(cur.right);
}
}
3.二叉树的最近公共祖先
思路:此题要使用后序遍历,因为有一个回溯的思想,将结果返回到根节点
代码要求:
1.遇到p或者q就返回当前节点
2.当节点左右都不为空时就往上返回这个答案节点
3.当节点左或者右一个为空时就返回不为空的那个节点(此结果包含了第二种可能:p就是q的祖先)
class Solution {
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(right != null && left != null) return root;
else if(right == null && left != null) return left;
else if(right != null && left == null) return right;
else return null;
}
}