代码随想录day21

代码随想录day21

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

class Solution {
    TreeNode pre;// 记录上一个遍历的结点
    int result = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
       if(root==null)return 0;
       traversal(root);
       return result;
    }
    public void traversal(TreeNode root){
        if(root==null)return;
        //左
        traversal(root.left);
        //中
        if(pre!=null){
            result = Math.min(result,root.val-pre.val);
        }
        pre = root;
        //右
        traversal(root.right);
    }
}

501.二叉搜索树中的众数

class Solution {
    
    HashMap<Integer, Integer> keyToFreq = new HashMap<>();
    HashMap<Integer, LinkedHashSet<Integer>> freqToKey = new HashMap<>();
    int maxFreq = 0;
    public int[] findMode(TreeNode root) {
        recursion(root);
        return freqToKey.get(maxFreq).stream().mapToInt(x -> x).toArray();
    }

    private void recursion(TreeNode root) {
        if (root == null) {
            return;
        }
        recursion(root.left);
        keyToFreq.put(root.val, keyToFreq.getOrDefault(root.val, 0) + 1);
        int key = root.val;
        int freq = keyToFreq.get(root.val);
        maxFreq = Math.max(freq, maxFreq);
        freqToKey.putIfAbsent(freq, new LinkedHashSet<Integer>());
        freqToKey.get(freq).add(key);
        recursion(root.right);
    }
}


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

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) return right; 
        if(right == null) return left;
        return root; 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值