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

Leetcode (力扣)做题记录 hot100(543,102,35,101)

力扣第543题:二叉树的直径

543. 二叉树的直径 - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {private int ans;public int diameterOfBinaryTree(TreeNode root) {ans = 0;dfs(root);return ans;}private int dfs(TreeNode root){if(root == null){return 0;}int l = dfs(root.left);int r = dfs(root.right);ans =  Math.max(ans,l + r);//计算最大路径return Math.max(l ,r) +1 ;//比较左和右谁大}
}
力扣第102题:二叉树的层序遍历

102. 二叉树的层序遍历 - 力扣(LeetCode)

首先创建一个队列用于不断弹出元素,首先先把root进去,然后取值,并把null排除,不断的向队列里面添加后续节点。

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {ArrayList<List<Integer>> arrayList = new ArrayList<>();if(root == null){return arrayList;}Deque<TreeNode> deque = new LinkedList<>();deque.offer(root);while(!deque.isEmpty()){ArrayList<Integer> valList = new ArrayList<>();int n = deque.size();for(int i = 0;i< n ;i++){TreeNode s = deque.poll();valList.add(s.val);if(s.left != null){deque.offer(s.left);}if(s.right != null){deque.offer(s.right);}}arrayList.add(valList);} return arrayList;}
}

力扣第35题:搜索插入位置

35. 搜索插入位置 - 力扣(LeetCode)

二分查找

class Solution {public int searchInsert(int[] nums, int target) {int left = 0;int right = nums.length - 1;while(left <= right){int mid = (left + right) /2;if(target < nums[mid]){right = mid - 1;}else if(target > nums[mid]){left = mid +1;}else{return mid;}}return left;}
}
 
力扣第70题:爬楼梯

70. 爬楼梯 - 力扣(LeetCode)

class Solution {public int climbStairs(int n) {int p =0 ,q = 0,r = 1;for(int i = 0; i <n;i++){p =q;q = r;r = p +q;}return r;}
}
 

 本文相关图片资源来自于网络中,如有侵权请联系删除!

http://www.xdnf.cn/news/371593.html

相关文章:

  • AI:PS软件:ps软件中如何使用人工智能(AI)?
  • SierraNet协议分析使用指导[RDMA]| 如何设置 NVMe QP 端口以进行正确解码
  • 画立方体软件开发笔记 js three 投影 参数建模 旋转相机 @tarikjabiri/dxf导出dxf
  • 代码随想录第41天:图论2(岛屿系列)
  • Git简介和发展
  • 代码复用与分层
  • 双目视觉系统中,极线校正(Epipolar Rectification)与单应性矩阵/多平面单应性模型
  • 通过推测搜索加速大型语言模型推理 (SpecSearch) 论文总结
  • 零基础入门MySQL:10分钟搞定数据库基本操作
  • tryhackme——Enumerating Active Directory
  • 【Linux】冯诺依曼体系结构和操作系统的理解
  • Webug4.0通关笔记25- 第30关SSRF
  • JS较底层的用法,几类简单介绍
  • 计算机网络基础科普
  • C语言复习--柔性数组
  • 如何在mac上使用便利贴
  • 青少年编程与数学 02-019 Rust 编程基础 06课题、容器类型
  • Docker镜像搬运工:save与load命令的实战指南
  • 【Android】文件分块上传尝试
  • 【金仓数据库征文】学校AI数字人:从Sql Server到KingbaseES的数据库转型之路
  • 基于GF域的多进制QC-LDPC误码率matlab仿真,译码采用EMS算法
  • Spring之AOP
  • 信息检索(包含源码)
  • 服务预热原理
  • 动态路由EIGRP的配置
  • AutoGen+Deepseek+chainlit的简单使用
  • iOS瀑布流布局的实现(swift)
  • HNUST湖南科技大学-软件测试期中复习考点(保命版)
  • Kubernetes应用发布方式完整流程指南
  • Dia浏览器:AI驱动浏览网页,究竟怎么样?(含注册申请体验流程)