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

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

题目链接:530.二叉搜索树的最小绝对差

思路:中序遍历,用pre节点记录cur节点的前一个节点的值。

class Solution {
    int result = Integer.MAX_VALUE;
    TreeNode pre = null;
    public int getMinimumDifference(TreeNode root) {
        traversal(root);
        return result;
    }
    private void traversal(TreeNode cur){
        if(cur == null)return;
        traversal(cur.left);
        if(pre!=null){
            result = Math.min(result,cur.val-pre.val);
        }
        pre = cur;
        traversal(cur.right);
    }
}

501.二叉搜索树中的众数

题目链接:501.二叉搜索树中的众数

思路:遍历元素出现频率可以将相邻两个元素进行比较,输出出现频率最高的元素。用count存储当前元素出现频率,maxCount存储最大频率,二者进行比较。当count>maxCount的时候,更新maxCount并清空结果集result。

class Solution {
    TreeNode pre = null;
    int count = 0;
    int maxCount = 0;
    ArrayList<Integer> result;
    public int[] findMode(TreeNode root) {
        result = new ArrayList<>();
        traversal(root);
        int[] res = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            res[i] = result.get(i);
        }
        return res;
    }
    public void traversal(TreeNode cur){
        if(cur == null)return;
        traversal(cur.left);
        if(pre == null){
            count = 1;
        }else if(pre.val == cur.val){
            count++;
        }else{
            count = 1;
        }
        pre = cur;
        if(count == maxCount)result.add(cur.val);
        if(count > maxCount){
            maxCount = count;
            result.clear();
            result.add(cur.val);
        }
        traversal(cur.right);
    }
}

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

题目链接:236. 二叉树的最近公共祖先

思路:遍历过程中遇到p或q返回,对左子树和右子树进行递归操作。左与右的处理逻辑:左右都不为空返回根节点,左为空右不为空返回右节点,左不为空右为空返回左节点。

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;
        }else if(left==null && right!=null){
            return right;
        }else if(left!=null&&right==null){
            return left;
        }
        else{
            return null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值