530.二叉搜索树的最小绝对差
二叉搜索树,二叉搜索树可是有序的。
遇到在二叉搜索树上求什么最值啊,差值之类的,就把它想成在一个有序数组上求最值,求差值,这样就简单多了。
class Solution {
TreeNode pre;
int result=Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root==null) return 0;
trav(root);
return result;
}
public void trav(TreeNode root){
if(root==null) return;
trav(root.left);
if(pre!=null){
int tmp=Math.abs(root.val-pre.val);
if(tmp<result) result=tmp;
}
pre=root;
trav(root.right);
}
}
501.二叉搜索树中的众数
class Solution {
ArrayList<Integer> record;
int Maxcount;
int count;
TreeNode pre;
public int[] findMode(TreeNode root) {
record=new ArrayList<Integer>();
Maxcount=0;
count=0;
find_zhongshu(root);
int[] res=new int[record.size()];
for(int i=0;i<record.size();i++){
res[i]=record.get(i);
}
return res;
}
public void find_zhongshu(TreeNode root){
if(root==null) return;
find_zhongshu(root.left);
if(pre!=null){
if(root.val==pre.val){
count++;
}
else count=1;
}
else count=1;
if(count>Maxcount){
Maxcount=count;
record.clear();
record.add(root.val);
}
else if(count == Maxcount){
record.add(root.val);
}
pre=root;
find_zhongshu(root.right);
}
}
236. 二叉树的最近公共祖先
很怕笔试遇到这个题的,已经看过很多遍了
一开始这么判断。但是这样没考虑到本身是自己的公共祖先的情况
if (left==p||left==q) return left;
if(right==p||right==q) return 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) return null;
else if(left==null&&right!=null) return right;
else if(left!=null&&right==null) return left;
else return root;
}
}
这个每次递归的单次逻辑页比较难想