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

代码随想录算法训练营day21 | 513.找树左下角的值、112. 路径总和、106.从中序与后序遍历序列构造二叉树

513.找树左下角的值

迭代法比较简单,层序遍历,找到最下面一层的第一个节点。题目已经说明节点数>=1了

class Solution:def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:queue = collections.deque()queue.append(root)result = root.valwhile queue:size = len(queue)for i in range(size):node = queue.popleft()if i == 0:result = node.valif node.left:queue.append(node.left)if node.right:queue.append(node.right)return result

递归法

题解中遇到叶子节点并且当前深度比最大深度更大时更换结果值,但是最深的节点必定是叶子节点,所以不必判断是叶子节点

class Solution:def __init__(self):self.result = 0self.max_depth = 0def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:self.getValue(root, 1)return self.resultdef getValue(self, node, depth):if not node:returnif depth > self.max_depth:self.max_depth = depthself.result = node.valself.getValue(node.left, depth+1)self.getValue(node.right, depth+1)

112. 路径总和

class Solution:def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:if not root:return Falsereturn self.traversal(root, 0, targetSum)def traversal(self, node, cur_sum, target_sum):if not node:return Falsecur_sum += node.valif not node.left and not node.right:if cur_sum == target_sum:return Truereturn self.traversal(node.left, cur_sum, target_sum) or self.traversal(node.right, cur_sum, target_sum)下面的代码思路更清晰
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
class Solution:def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:if not root:return Falsereturn self.traversal(root, targetSum-root.val)def traversal(self, node, count):if not node.left and not node.right:return count == 0if node.left:if self.traversal(node.left, count-node.left.val):return Trueif node.right:if self.traversal(node.right, count-node.right.val):return Truereturn False

路径总和:返回是否存在路径

路径总和II:返回满足条件的所有路径

下面为路径总和II的代码

class Solution:def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:result = []if not root:return resultself.getPath(root, [root.val], result, targetSum-root.val)return resultdef getPath(self, node, path, result, count):if not node.left and not node.right:if count == 0:result.append(path[:])if node.left:path.append(node.left.val)self.getPath(node.left, path, result, count-node.left.val)path.pop()if node.right:path.append(node.right.val)self.getPath(node.right, path, result, count-node.right.val)path.pop()

106.从中序与后序遍历序列构造二叉树

下面为每层递归定义了新的vector(就是数组),既耗时又耗空间。可以使用索引的方式,每次确定区间的左右索引

class Solution:def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:if len(inorder) <= 0:returnvalue = postorder[-1]index = inorder.index(value)left = self.buildTree(inorder[0:index], postorder[0:index])right = self.buildTree(inorder[index+1:], postorder[index:-1])return TreeNode(value, left, right)

105. 从前序与中序遍历序列构造二叉树

class Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:if not preorder:returnvalue = preorder[0]index = inorder.index(value)left = self.buildTree(preorder[1:index+1], inorder[0:index])right = self.buildTree(preorder[index+1:], inorder[index+1:])return TreeNode(value, left, right)

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

相关文章:

  • 微信小程序知识点归纳(一)
  • wangEditor富文本编辑器与layui图片上传
  • 爬虫学习:XPath提取网页数据
  • 【雅思写作】Vince9120雅思小作文笔记——P1 Intro(前言)
  • 【面试干货】HTTPS 工作原理
  • Cocos Creator 中编码规范 (6)
  • Vue3:menu导航栏出现多个同一跳转路径的菜单处理
  • SAM轻量化应用Auto-SAM、Group-Mix SAM、RAP-SAM、STLM
  • 深度优化搜索DFS使用详解,看这篇就够了!!!
  • Apache SeaTunnel 正式发布2.3.5版本,功能增强及多个Bug修复
  • interview_bak
  • layui 数据表格 自动定位新增行位置
  • window10下安装ubuntu系统以及docker使用
  • Netty核心组件介绍
  • 代码审计平台sonarqube的安装及使用
  • C++ 使用nlohmann/json.hpp库读写json字符串
  • 3GPP官网下载协议步骤
  • 【JAVA】Git 的基本概念和使用方式
  • C++多态实现原理详解
  • [数据集][目标检测]交通灯检测数据集VOC+YOLO格式2600张1类别
  • 关于测试用例
  • 一起长锈:3 类型安全的Rust宏(从Java与C++转Rust之旅)
  • 《金融研究》:普惠金融改革试验区DID工具变量数据(2012-2023年)
  • Prompt|Kimi高阶技巧,99%的人都不知道
  • 采购管理软件:采购自动化提高效率的5种方式
  • Android App开机启动
  • 服务器直连电脑(盒子直连电脑)电脑需要设置为固定ip才能访问盒子
  • 【设计模式】之代理模式(两种)
  • 【工具篇】-什么是.NET
  • OmniReader Pro mac激活版:智慧阅读新选择,开启高效学习之旅