530.二叉搜索树的最小绝对差
思路
题解思路:二叉搜索树本身是有序的树,中序遍历能够得到有序的结果
代码
class Solution {
TreeNode pre;
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
midOrder(root);
return result;
}
public void midOrder(TreeNode root){
if(root == null) return;
midOrder(root.left);
if(pre != null){
result = Math.min(result,root.val-pre.val);
}
pre = root;
midOrder(root.right);
}
}
501.二叉搜索树中的众数
思路
题解思路:
如果不是二叉搜索树,最直观的方法一定是把这个树都遍历了,用map统计频率,把频率排个序,最后取前面高频的元素的集合
思路:仍然按照最小绝对差的做法,设定一个pre指针,利用二叉搜索树的中序遍历是有序的特性,统计每个元素出现的个数,当某元素出现的次数更大,就计入,且删除之前记录的值,当相等,就直接加入。
代码
class Solution {
List<Integer> res = new ArrayList<>();
TreeNode pre = null;
int count = 0;
int maxc = 0;
public int[] findMode(TreeNode root) {
midOrder(root);
int[] res_i = new int[res.size()];
for(int i = 0;i<res.size();i++){
res_i[i] = res.get(i);
}
return res_i;
}
public void midOrder(TreeNode root){
if(root == null) return;
midOrder(root.left);
if(pre ==null || pre.val != root.val){
count=1;
}else{
count++;
}
if(count>maxc){
maxc = count;
res.clear();
res.add(root.val);
}else if(count == maxc){
res.add(root.val);
}
pre = root;
midOrder(root.right);
}
}
236. 二叉树的最近公共祖先
思路
题解思路:后序遍历就是天然的回溯,从下到上进行
如果left 和 right都不为空,说明此时root就是最近公共节点。这个比较好理解
如果left为空,right不为空,就返回right,说明目标节点是通过right返回的,反之依然。
代码
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode 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) { // 若未找到节点 p 或 q
return null;
}else if(left == null && right != null) { // 若找到一个节点
return right;
}else if(left != null && right == null) { // 若找到一个节点
return left;
}else { // 若找到两个节点
return root;
}
}
}