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

代码随想录算法训练营Day15

654.最大二叉树

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

前序递归、循环不变量

class Solution {public TreeNode constructMaximumBinaryTree(int[] nums) {return findmax(nums,0,nums.length);}public TreeNode findmax(int[] nums,int leftindex,int rightindex){if(rightindex==leftindex){return null;}if(rightindex-leftindex==1){return new TreeNode(nums[leftindex]);}int max=nums[leftindex];int maxindex=leftindex;for(int i=leftindex;i<rightindex;i++){if(nums[i]>max){max=nums[i];maxindex=i;}}TreeNode root=new TreeNode(max);root.left=findmax(nums,leftindex,maxindex);root.right=findmax(nums,maxindex+1,rightindex);return root;}
}

617.合并二叉树

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

前序递归

class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {if(root1==null)return root2;if(root2==null)return root1;root1.val+=root2.val;root1.left=mergeTrees(root1.left,root2.left);root1.right=mergeTrees(root1.right,root2.right);return root1;}
}

700.二叉搜索树中的搜索

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

class Solution {public TreeNode searchBST(TreeNode root, int val) {if(root==null){return null;}if(val>root.val){return searchBST(root.right,val);}if(val<root.val){return searchBST(root.left,val);}return root;}
}

98.验证二叉搜索树

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

中序递归

class Solution {public boolean isValidBST(TreeNode root) {List<Integer> res=new ArrayList<>();midorder(root,res);for(int i=0;i<res.size()-1;i++){if(res.get(i)>=res.get(i+1)){return false;}}return true;}public void midorder(TreeNode root,List<Integer> res){if(root==null){return;}midorder(root.left,res);res.add(root.val);midorder(root.right,res);}
}

http://www.lryc.cn/news/449988.html

相关文章:

  • Thinkphp/Laravel旅游景区预约系统的设计与实现
  • SpringCloud学习记录|day1
  • Elasticsearch讲解
  • Linux嵌入式有发展吗,以及对uboot,kernel,rootfs的领悟
  • 基于Springboot+Vue的公寓管理系统(含源码+数据库)
  • 多功能声学气膜馆:承载梦想与希望的舞台—轻空间
  • 【线程】线程池
  • 输出 / 目录下所有目录文件的大小并排序
  • 【hot100-java】【编辑距离】
  • 随手记:牛回速归
  • UI设计师面试整理-设计过程和方法论
  • ACM 纳新每日一题 4329: 三进制
  • WebGIS包括哪些技术栈?怎么学习?
  • 无人机之集群控制及应用
  • AV1 Bitstream Decoding Process Specification--[9]:语法结构语义-5
  • APISIX 联动雷池 WAF 实现 Web 安全防护
  • 音频剪辑还能在线做?以前的我真是OUT了,效果秒杀专业软件
  • Library介绍(三)
  • VMware搭建DVWA靶场
  • 使用 Llama-index 实现的 Agentic RAG-Router Query Engine
  • 一行命令将Cmder添加到系统右键菜单中----配置环境
  • 【系统架构设计师】专题:基于构件的软件工程考点
  • 目前最好用的爬虫软件是那个?
  • 运营计划管理——电商运营(案例分享)
  • 【WRF工具】WRF Domain Wizard第二期:服务器中下载及安装
  • 信安 实验1 用Wireshark分析典型TCP/IP体系中的协议
  • Halcon内部和外部函数,区分明白
  • 使用 pypdf 给 PDF 添加目录书签
  • 2025郑州台球展,河南台球展会,智能台球桌展3月举办
  • Vue下载静态文件