代码随想录算法训练营补打卡 day21 |530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236. 二叉树的最近公共祖先

代码随想录

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;
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值