代码随想录算法day17| 二叉树 part06||530.二叉搜索树的最小绝对差,501.二叉搜索树中的众数,236. 二叉树的最近公共祖先

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;

        
    }
}

这个每次递归的单次逻辑页比较难想

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值