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

代码随想录算法训练营day18 | 102.二叉树的层序遍历、226.翻转二叉树、101. 对称二叉树

102.二叉树的层序遍历

迭代法

层序遍历使用队列,同时记录每层的个数

class Solution:def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:res = []if not root:return resqueue = collections.deque()queue.append(root)while queue:size = len(queue)tmp = []for _ in range(size):node = queue.popleft()tmp.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)res.append(tmp)return res

递归法

class Solution:def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:result = []self.order(root, result, 0)return resultdef order(self, cur, result, depth):if not cur:returnif len(result) == depth:result.append([])result[depth].append(cur.val)self.order(cur.left, result, depth+1)self.order(cur.right, result, depth+1)

226.翻转二叉树

递归法

递归时,中序遍历会重复翻转部分,本题只能使用前序遍历和后序遍历

能够在看题解之前写出来,有进步

class Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:# 前序遍历if not root:returnroot.left, root.right = root.right, root.leftself.invertTree(root.left)self.invertTree(root.right)return rootclass Solution:def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:# 后序遍历if not root:returnself.invertTree(root.left)self.invertTree(root.right)root.left, root.right = root.right, root.leftreturn root

101. 对称二叉树

递归法

class Solution:def isSymmetric(self, root: Optional[TreeNode]) -> bool:if not root:return Truereturn self.symmetric(root.left, root.right)def symmetric(self, left, right):if (not left and right) or (not right and left):return Falseif not left and not right:return Trueif left.val != right.val:return Falsereturn self.symmetric(left.left, right.right) and self.symmetric(left.right, right.left)

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

相关文章:

  • 工厂自动化升级改造参考(01)--设备通信协议详解及选型
  • 数据结构与算法之经典排序算法
  • VSCode通过SSH连接虚拟机Ubuntu失败
  • 在Codelab对llama3做Lora Fine tune微调
  • KEIL 5.38的ARM-CM3/4 ARM汇编设计学习笔记13 - STM32的SDIO学习5 - 卡的轮询读写擦
  • 【C++】HP-Socket(三):UdpClient、UdpServer、UdpCast、UdpNode的区别
  • java设计模式六 访问者
  • 中间件研发之Springboot自定义starter
  • libcity笔记:添加新模型(以RNN.py为例)
  • Ansible---自动化运维工具
  • 5.Git
  • 探索中位数快速排序算法:高效寻找数据集的中间值
  • 密码学《图解密码技术》 记录学习 第十五章
  • 如何在 Ubuntu 16.04 上为 Nginx 创建自签名 SSL 证书
  • 5.协议的编解码
  • 数据结构基础| 线性表
  • 嵌入式学习
  • sass-loader和node-sass与node版本的依赖问题
  • 基于BP神经网络的QPSK解调算法matlab性能仿真
  • Linux服务器常用巡检命令
  • VSCode 配置 CMake
  • ​《MATLAB科研绘图与学术图表绘制从入门到精通》示例:绘制德国每日风能和太阳能产量3D线图
  • 【信息系统项目管理师知识点速记】质量管理:控制质量
  • 【云原生】Pod 的生命周期(一)
  • Golang | Leetcode Golang题解之第71题简化路径
  • Unreal游戏GPU性能优化检测模式全新上线
  • 设计网页用什么软件
  • ⑪ - 测试工程师通识指南
  • RabbitMQ知识点总结和复习
  • ContEA阅读笔记