当前位置: 首页 > article >正文

代码随想录算法训练营Day16

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

力扣题目链接:. - 力扣(LeetCode)

中序递归

class Solution {
    TreeNode pre;
    int res=Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        midorder(root);
        return res;
    }
    public void midorder(TreeNode root){
        if(root==null){
            return;
        }
        midorder(root.left);
        if(pre!=null){
            res=Math.min(res,root.val-pre.val);
        }
        pre=root;
        midorder(root.right);
    }
}

501.二叉搜索树中的众数

力扣题目链接:. - 力扣(LeetCode)

中序递归

class Solution {
    int count=0;
    int maxcount=0;
    TreeNode pre=null;
    public int[] findMode(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        midorder(root,res);
        int[] result=new int[res.size()];
        for(int i=0;i<res.size();i++){
         result[i]=res.get(i);
        }
        return result;
    }
    public void midorder(TreeNode root,List<Integer> res){
        if(root==null){
            return;
        }
        midorder(root.left,res);      
        if(pre==null||root.val!=pre.val){
            count=1;
        }else{
            count++;
        }
        if(count>maxcount){
            res.clear();
            res.add(root.val);
            maxcount=count;
        }else if(count==maxcount){
            res.add(root.val);
        }
        pre=root;
        midorder(root.right,res);
    }
}

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

力扣题目链接:. - 力扣(LeetCode)

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&&right==null){
            return left;
        }
        if(left==null&&right!=null){
            return right;
        }
        return root;
    }
}


http://www.kler.cn/news/325801.html

相关文章:

  • Threejs绘制圆锥体
  • 1.8 软件业务测试
  • 试填+组合数学,CF 1648C - Tyler and Strings
  • 【Linux】Linux内核结构基础
  • 缓存池和数据库连接池的使用(Java)
  • Vue 中自定义指令的探索与实践
  • ZYNQ:点亮LED灯
  • 每天一个数据分析题(四百七十六)- 线性回归建模
  • Go语言匿名字段使用与注意事项
  • Markdown 字体颜色
  • postgreSql常用操作
  • Spring Boot 多线程事务管理:使用 CyclicBarrier 和 PlatformTransactionManager 实现全局事务控制
  • Docker-3.启动
  • Vue3+FastAPI中Token的刷新机制(含代码示例)
  • 鸿蒙HarmonyOS之选择相册文件(照片/视频)方法
  • MySQL之分库分表后带来的“副作用”你是怎么解决的?
  • Servlet 3.0新特征
  • 新能源汽车储充机器人:能源高效与智能调度
  • 【2024.9.29练习】R 格式
  • P9241 [蓝桥杯 2023 省 B] 飞机降落
  • 【MySQL】查询原理 —— B+树查询数据全过程
  • docker安装Portainer CE
  • 华为eNSP:端口隔离
  • 【AI大模型】Prompt Engineering
  • tr命令:替换文本中的字符
  • PHP array+array与array_merge()的区别
  • Vue.js与Flask/Django后端的协同开发研究
  • 2-3树(2-3 Tree):原理、常见算法及其应用
  • JAVA开源项目 新闻推荐系统 计算机毕业设计
  • Flink 本地 idea 调试开启 WebUI