530.二叉搜索树的最小绝对差
力扣题目链接:. - 力扣(LeetCode)
中序递归
class Solution {
TreeNode pre;
int res=Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
midorder(root);
return res;
}
public void midorder(TreeNode root){
if(root==null){
return;
}
midorder(root.left);
if(pre!=null){
res=Math.min(res,root.val-pre.val);
}
pre=root;
midorder(root.right);
}
}
501.二叉搜索树中的众数
力扣题目链接:. - 力扣(LeetCode)
中序递归
class Solution {
int count=0;
int maxcount=0;
TreeNode pre=null;
public int[] findMode(TreeNode root) {
List<Integer> res=new ArrayList<>();
midorder(root,res);
int[] result=new int[res.size()];
for(int i=0;i<res.size();i++){
result[i]=res.get(i);
}
return result;
}
public void midorder(TreeNode root,List<Integer> res){
if(root==null){
return;
}
midorder(root.left,res);
if(pre==null||root.val!=pre.val){
count=1;
}else{
count++;
}
if(count>maxcount){
res.clear();
res.add(root.val);
maxcount=count;
}else if(count==maxcount){
res.add(root.val);
}
pre=root;
midorder(root.right,res);
}
}
236. 二叉树的最近公共祖先
力扣题目链接:. - 力扣(LeetCode)
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;
}
if(left!=null&&right==null){
return left;
}
if(left==null&&right!=null){
return right;
}
return root;
}
}