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

目录

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

501 二叉搜索树的众数

236 二叉树的最近公共祖先


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

利用二叉搜索树的性质,对树进行中序遍历,过程中统计差值。

class Solution {
    int res = Integer.MAX_VALUE;
    TreeNode pre;
    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return res;
    }
    private void dfs(TreeNode cur){//中序遍历 
        if(cur == null)return;
        dfs(cur.left);//左
        if(pre != null)res = Math.min(res,cur.val - pre.val);//中
        pre = cur;
        dfs(cur.right);//右
    }
}

时间复杂度O(n)

空间复杂度O(n) 

501 二叉搜索树的众数

 利用二叉搜索树的性质,对树进行中序遍历,由于是有序的所以有如下三种情况:

  1. 统计完一个值的出现次数之后如果遇到了出现次数更多的值,将这个值清除后加入下一个值到resList。
  2. 如果二者出现次数相同则保留原来值并且加入下一个值。
  3. 如果下一个值小于之前值则不做处理。
class Solution {
    int count;
    int maxCount;
    List<Integer>resList;
    TreeNode pre;
    public int[] findMode(TreeNode root) {
        resList = new ArrayList<>();
        maxCount = -1;
        count = 0;
        pre = null;
        dfs(root);
        int res[] = new int[resList.size()];
        for(int i = 0;i < res.length;i++){
            res[i] = resList.get(i);
        }
        return res;
    }
    void dfs(TreeNode root){
        if(root == null)return;
        dfs(root.left);
        if(pre == null || pre.val != root.val){
            count = 1;
        }else{
            count++;
        }
        if(count > maxCount){
            resList.clear();
            resList.add(root.val);
            maxCount = count;
        }else if(count == maxCount)resList.add(root.val);
        pre = root;
        dfs(root.right);
    }
}

时间复杂度O(n)

空间复杂度O(n) 

236 二叉树的最近公共祖先

后序遍历二叉树,如果遍历到q或p或null节点就返回,如果没有则继续递归遍历左子树和右子树,并用l和r存储遍历结果。

此时有如下四种情况:

  1. l找到p或q,r未找到。返回l
  2. r找到p或q,l未找到,返回r
  3. l与r都没找到p或q,则返回null
  4. l找到了p或者q,r找到了剩下的一个,则该节点为最近公共祖先节点,返回该节点
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == q || root == p)return root;
        //后序遍历 左右中
        TreeNode l = lowestCommonAncestor(root.left,p,q);
        TreeNode r = lowestCommonAncestor(root.right,p,q);
        if(l == null && r == null)return null;
        else if(l == null && r != null)return r;
        else if(l != null && r == null)return l;
        else return root;
    }
}

时间复杂度O(n)

空间复杂度O(n) 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值