算法跟学Day21【代码随想录】

本文介绍了三个与二叉搜索树相关的LeetCode问题的解决方案:找到树中最小的绝对差值、查找树中的众数以及确定两个节点的最近公共祖先。提供的Java代码分别解决了这些问题,涉及中序遍历和递归等算法技巧。
摘要由CSDN通过智能技术生成

第六章 二叉树part07

大纲

● 530.二叉搜索树的最小绝对差
● 501.二叉搜索树中的众数
● 236. 二叉树的最近公共祖先

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

代码

class Solution {
    int min = Integer.MAX_VALUE, pre = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return 0;
        getMinimumDifference(root.left);
        int dif = Math.abs(pre - root.val);
        min = dif > min ? min : dif;
        pre = root.val;
        getMinimumDifference(root.right);
        return min;
    }
}

leetcode 501 二叉搜索树中的众数

代码

class Solution {
    List<Integer> res = new ArrayList<>();
    int count = 0, maxCount = 0, pre = Integer.MAX_VALUE;
    public int[] findMode(TreeNode root) {
        inorder(root);
        int[] resNum = new int[res.size()];
        for (int i = 0; i < res.size(); i++) resNum[i] = res.get(i);
        return resNum;
    }

    public void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        if (pre == Integer.MAX_VALUE) count = 1;
        else if (pre == node.val) count++;
        else count = 1;
        pre = node.val;
        if (count == maxCount) res.add(node.val);
        else if (count > maxCount) {
            maxCount = count;
            res.clear();
            res.add(node.val);
        }
        inorder(node.right);
    }
}

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

代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值