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

530. 二叉搜索树的最小绝对差

难度简单404

给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。

差值是一个正数,其数值等于两值之差的绝对值。

class Solution {
    int min = Integer.MAX_VALUE;
    int pre = -1;
    public int getMinimumDifference(TreeNode root) {
        inorder(root);
        return min;
    }
    public void inorder(TreeNode root){
        if(root == null)return;
        inorder(root.left);
        if(pre == -1){
            pre = root.val;
        }else{
            min = Math.min(min,root.val-pre);
            pre = root.val;
        }
        inorder(root.right);
    }
}

 

501. 二叉搜索树中的众数

难度简单553

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

  • 结点左子树中所含节点的值 小于等于 当前节点的值
  • 结点右子树中所含节点的值 大于等于 当前节点的值
  • 左子树和右子树都是二叉搜索树
class Solution {
    int maxCount = 1;
    ArrayList<Integer> list = new ArrayList<>();
    int count = 0;
    TreeNode pre = null;
    public int[] findMode(TreeNode root) {
        inorder(root);
        
        int[] res = new int[list.size()];
        for(int i =0;i <  list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }
    public void inorder(TreeNode root){
        if(root == null)return;
        inorder(root.left);
        if(pre == null){
            pre = root;
            count = 1;
            maxCount = 1;
        }else{
            if(root.val == pre.val){
                count++;
            }else{
                count = 1;
                pre = root;
            }
        }
        if(count > maxCount){
            list = new ArrayList<>();
            list.add(root.val);
            maxCount = count;
        }else if(count == maxCount ){
            list.add(root.val);
        }
        inorder(root.right);
    }
}

 

236. 二叉树的最近公共祖先

难度中等2057

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null)return root;
        if(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 root;
        if(left != null)return left;
        if(right != null)return right;
        return null;
    }
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值