【5.09 代随_21day】 二叉搜索树的最小绝对差、二叉搜索树中的众数、二叉树的最近公共祖先

本文介绍了二叉搜索树的三个关键问题的解决方案:如何找到树的最小绝对差,如何找到众数以及如何找到最近的公共祖先。这些问题都利用了递归和二叉树的特性,如中序遍历和后序遍历。递归方法在处理二叉搜索树时能有效简化问题,而二叉树的结构则帮助我们高效地找到所需信息。
摘要由CSDN通过智能技术生成


二叉搜索树的最小绝对差

力扣连接:530. 二叉搜索树的最小绝对差(简单)

1.递归的方法

递归的图解步骤

在这里插入图片描述

关键点

  • 需要用一个pre节点记录一下cur节点的前一个节点。

递归代码

// 递归法
class Solution {
    TreeNode pre;   //记录前一个节点
    Integer min = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        getMinimum(root);
        return min;

    }

    public void getMinimum(TreeNode cur) {
        if(cur==null) return;
        getMinimumDifference(cur.left);

        if(pre!=null){
            min = Math.min(min, cur.val-pre.val);
        }
        pre = cur;

        getMinimumDifference(cur.right);
    }
}


二叉搜索树中的众数

力扣连接:501.二叉搜索树中的众数(简单)

1.递归的方法

既然是搜索树,它中序遍历就是有序的。

递归的图解步骤

在这里插入图片描述

关键点

  • 需要用一个pre节点记录一下cur节点的前一个节点。
  • 当 count > maxCount 时,清空列表,再加入节点值

递归代码

class Solution {
    int count = 0;
    int maxCount = 0;
    TreeNode pre; //记录前一个节点
    List<Integer> result = new ArrayList<>();
    public int[] findMode(TreeNode root) {
        searchMax(root);
        return result.stream().mapToInt(Integer::valueOf).toArray();
    }

    public void searchMax(TreeNode cur){
        if(cur==null) return;

        searchMax(cur.left);

        if(pre==null||cur.val!=pre.val){
            count = 1;
        }else{
            count++;
        }

        if(count>maxCount){
            maxCount = count;
            result.clear();
            result.add(cur.val);
        }else if(count==maxCount){
            result.add(cur.val);
        }

        pre = cur;

        searchMax(cur.right);
    }
}


二叉树的最近公共祖先

力扣连接:236. 二叉树的最近公共祖先(简单)

自底向上查找就可以找到公共祖先

二叉树回溯的过程就是从低到上

后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。

图解步骤

在这里插入图片描述

代码

class Solution {
    //后序遍历
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || root==p || root==q) return root;

        TreeNode leftNode = lowestCommonAncestor(root.left, p, q);  //左
        TreeNode rightNode = lowestCommonAncestor(root.right, p, q);    //右

        //中
        if(leftNode==null && rightNode!=null){
            return rightNode;

        }else if(leftNode!=null && rightNode==null){
            return leftNode;

        }else if(leftNode==null && rightNode==null){
            return null; 

        }else{
            return root;
        }

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值