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

LeeCode打卡第二十三天

LeeCode打卡第二十三天

第一题:二叉树的最大深度(LeeCode第104题):

给定一个二叉树 root ,返回其最大深度。二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。


主要思想:在层次遍历的基础上进行了修改,主要是用到了辅助队列

/*** 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 {public int maxDepth(TreeNode root) {if(root == null) return 0;Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.add(root);int size = queue.size();int len = 0;while(!queue.isEmpty()){int n = queue.size();for(int i = 0; i < n; i++){TreeNode cur = queue.poll();if(cur.left != null) queue.add(cur.left);if(cur.right != null) queue.add(cur.right);}len++;}return len;}
}

第二题:二叉树的最大深度(LeeCode第104题):

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。


主要思想:用递归的方法,每次只交换左右两个孩子的值

/*** 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 {public TreeNode invertTree(TreeNode root) {if(root == null) return null;invertTree(root.left);invertTree(root.right);swapChildren(root);return root;} public void swapChildren(TreeNode root){TreeNode tmp = root.left;root.left = root.right;root.right = tmp;}
}

http://www.mrgr.cn/news/25328.html

相关文章:

  • 【算法】冒泡排序
  • ETC SLAVE状态解释
  • java的ReentrantLock原理
  • ffmpeg面向对象-rtsp拉流相关对象
  • Hash算法与Hash冲突
  • 【EI会议末轮截稿通知】第三届电子信息技术国际学术会议(EIT 2024)
  • 从制造业单项冠军到领航企业群,深圳要如何发力?
  • R语言论文插图模板第10期—正负柱状图
  • 攻防世界 CTF Pwn(一)
  • 提升开发效率的神器:编程工具盘点与应用体验
  • 再次进阶 舞台王者 第八季完美童模全球赛荣耀大使【梁悦源】赛场秀场超燃合集!
  • NoSQL之Redis配置与优化(2)
  • vue-router + el-menu
  • PMP证书速成秘籍:小白3月变身项目管理达人!
  • CLIP:Learning Transferable Visual Models From Natural Language Supervision
  • RK3568 初识
  • PyTorch----模型运维与实战
  • SAP B1 单据页面自定义 - 用户界面编辑字段
  • 谁破防了?低代码能代替程序员吗
  • 高并发内存池(4)——实现CentralCache