代码随想录Day18

题目列表

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

解题过程

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

题目描述

解题思路

二叉搜索树采用中序遍历,得到的结果就是有序的,要求得最小的绝对差,需要遍历一整棵树,只要保证一直是后一个减前一个的值,就是差的绝对值。
递归函数参数与返回值:参数是树的节点,无返回值,因为最后的结果一定要遍历一整棵树才能得到记录。
终止条件:当前节点为 null .
递归逻辑:左中右的顺序;“中”的处理逻辑:准备一个全局变量节点 pre 保存前一个节点,然后判断当前节点与 pre 的值的差是否是最小。

代码展示

class Solution {
    private int result = Integer.MAX_VALUE;
    private   TreeNode pre = null;
    public int getMinimumDifference(TreeNode root) {
        getMin(root);
        return result;
    }
    public void getMin(TreeNode root){
        if(root == null) return;

        getMin(root.left);
        if(pre != null){
            result = Math.min(result, root.val - pre.val);
        }
        pre = root;
        getMin(root.right);
    }
}

501.二叉搜索树中的众数

题目描述

解题思路

这道题的核心逻辑在中间节点的处理过程:
首先要记录当前节点的出现次数,然后要根据当前节点出现次数 count 来更新最大出现次数 maxCount :
如果 count 大于 maxCount ,就说明有了出现次数更多的众数,那么之前记录的“众数”就应该丢弃,而当前节点的值成为新的众数,然后 maxCount 更新为 count。
如果 count 等于 maxCount, 就说明这是新的众数,添加到结果集即可。

代码展示

class Solution {
    List<Integer> res = new ArrayList<>();
    int maxCount = 0;
    int count = 0;
    TreeNode pre = null;
    public int[] findMode(TreeNode root) {
        find(root);
        int[] result = new int[res.size()];
        int i = 0;
        for(int num : res){
           result[i++] = num;
        }
        return result;
    }
    public void find(TreeNode cur){
        if(cur == null) return;

        find(cur.left);

        //记录当前节点的count
        if(pre != null && pre.val == cur.val){
            count += 1;
        }else if(pre == null || pre.val != cur.val){
            count = 1;
        }
        pre = cur;
        //更新最大count
        if(count > maxCount){
            res.clear();
            maxCount = count;
            res.add(cur.val);
        }else if(count == maxCount){
            res.add(cur.val);
        }

        find(cur.right);

    }
}

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

题目描述

解题思路

这道题要“从下往上”遍历,但第一个传入的参数是 root ,所以要将结果一直 return 到树的根节点,也就是需要回溯。
采用后序遍历,递归:
递归函数返回值类型与参数:因为要返回最低公共祖先,所以返回值类型是 TreeNode, 参数就是树的节点和 p 和 q .
终止条件:当前节点为 null ,或 p ,或 q.
递归逻辑:后序遍历,先是左子树,再是右子树,然后处理:
如果左子树和右子树的返回值都不是 null, 说明当前节点的左右子树中有pq,此时它就是这个祖先,返回自己。
如果其中一个为空,那么说明pq其中出现在左子树或右子树,出现在哪边,就返回哪边的孩子节点。
如果都为 null ,返回 null.

代码展示

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

参考资料

代码随想录

posted @ 2025-05-15 20:39  cbdsszycfs  阅读(8)  评论(0)    收藏  举报