代码随想录算法训练营Day18

513. Find Bottom Left Tree Value

一开始的朴素思想是, Bottom Left Node一定是一个左子树衍生的叶子结点. 但实际会有cur节点没有左子树,而右子树就成为了这一层的leftmost.

终止条件只需要在depth 增加时, 更新叶子结点的取值即可.

前序递归 & 层序迭代

class Solution:def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:# 前序递归def traversal(cur: TreeNode, depth: int):nonlocal maxDepth, ansif not cur: returnif (not cur.left) and (not cur.right) and depth > maxDepth:maxDepth = depthans = cur.valtraversal(cur.left, depth + 1)traversal(cur.right, depth + 1)returnmaxDepth = - 1ans = 0traversal(root, 1)return ans# TC: O(N)# SC: O(log(N))
class Solution:def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:# 层序迭代q = [root]cur = rootmaxDepth = -1ans = 0depth = 0while q:depth += 1for _ in range(len(q)):cur = q.pop(0)if (not cur.left) and (not cur.right) and depth > maxDepth:maxDepth = depthans = cur.valif cur.left: q.append(cur.left)if cur.right: q.append(cur.right)return ans# 层序迭代 不需要depth变量的方法q = [root]cur = rootans = 0while q:for i in range(len(q)):cur = q.pop(0)if i == 0:ans = cur.valif cur.left: q.append(cur.left)if cur.right: q.append(cur.right)return ans

112. Path Sum

前序递归: 一遍过好耶

class Solution:def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:# 前序递归def traversal(cur: TreeNode, ss:int):if not cur: returnif not (cur.left or cur.right): res.append(ss + cur.val)if cur.left: traversal(cur.left, ss + cur.val)if cur.right: traversal(cur.right, ss + cur.val)returnres = []traversal(root, 0)return True if targetSum in res else False
class Solution:def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:# 前序递归: 简洁版# if not root: return False# if (not root.left) and (not root.right) and targetSum == root.val:#     return True# return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)# 层序迭代if not root: return Falseq = []q.append((root, root.val))while q:cur, curSum = q.pop(0)if (not cur.left) and (not cur.right) and (curSum == targetSum):return Trueif cur.left: q.append((cur.left, curSum + cur.left.val))if cur.right: q.append((cur.right, curSum + cur.right.val))return False

113. Path Sum II

前序递归:一遍过好耶

class Solution:def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:def dfs(cur: TreeNode, path: List, targetSum: int):if not cur: returnif (not cur.left) and (not cur.right) and targetSum == cur.val:res.append(path + [cur.val])if cur.left: dfs(cur.left, path+[cur.val], targetSum - cur.val)if cur.right: dfs(cur.right, path+[cur.val], targetSum - cur.val)return       if not root: return []res = []path = []dfs(root, path, targetSum)return res
class Solution:def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:# 层序迭代if not root: return []q = [(root, root.val, [root.val])] # Node, sum, pathres = []while q:cur, curSum, path = q.pop(0)if (not cur.left) and (not cur.right) and curSum == targetSum:res.append(path)if cur.left:q.append((cur.left, curSum+cur.left.val, path + [cur.left.val]))if cur.right:q.append((cur.right, curSum+cur.right.val, path + [cur.right.val]))return res

106. Construct Binary Tree from Inorder and Postorder Traversal

前序和后序的共同特点,左右子树区间连在一起,难以分开. 所以只有“中序+前序”或“中序+后序”才能恢复原二叉树.

class Solution:def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:if not postorder: return None # 终止条件# Inorder.length >= 1root = TreeNode(postorder[-1])# find the delimiter# ii = inorder.index(postorder[-1])ii = 0for ii in range(len(postorder)):if inorder[ii] == postorder[-1]: breakinorderLeft = inorder[:ii]inorderRight = inorder[ii+1:]postorderLeft = postorder[:len(inorderLeft)]postorderRight = postorder[len(inorderLeft):-1]root.left = self.buildTree(inorderLeft, postorderLeft)root.right = self.buildTree(inorderRight, postorderRight)return root

105. Construct Binary Tree from Preorder and Inorder Traversal

class Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:if not preorder: return Noneroot = TreeNode(preorder[0])index = inorder.index(preorder[0])inorderLeft = inorder[:index]inorderRight = inorder[index+1:]preorderLeft = preorder[1:1+len(inorderLeft)]preorderRIght = preorder[1+len(inorderLeft):]root.left = self.buildTree(preorderLeft, inorderLeft)root.right = self.buildTree(preorderRIght, inorderRight)return root

Day18-恶魔低语: [递归迭代], 两种方法掌握一下相关推荐

  1. 二叉树层序遍历分层[递归迭代两种思想+三种解法]

    层序遍历分层的递归迭代解法 前言 一.二叉树层序遍历分层 二.递归与迭代 总结 参考文献 前言 层序遍历作为二叉树遍历的基本遍历,一般来说只能用迭代来解.但是分层输出则既可用迭代,又可配合level用 ...

  2. NYOJ--C语言---Fibonacci数递归迭代两种解法

    题目描述 无穷数列1,1,2,3,5,8,13,21,34,55...称为Fibonacci数列,它可以递归地定义为F(n)=1 ...........(n=1或n=2)F(n)=F(n-1)+F(n ...

  3. 【剑指offer 07】用迭代和递归两种方法重构二叉树(python实现)

    本文讲解一个经典的面试题,使用 python 通过迭代和递归两种方法重构二叉树. 题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字 ...

  4. 最大团问题(使用递归和非递归两种方法)

    文章目录 问题描述 解决方法 递归回溯(递归) 迭代回溯(非递归) 测试样例及测试结果 问题描述 ​ 一个无向图 G = ( V , E ) G=(V,E) G=(V,E) , V V V 是点集, ...

  5. 递归和循环两种方法完成树的镜像转换

    /* copyright@nciaebupt 转载出处:http://blog.csdn.net/nciaebupt/article/details/8506038 题目:输入一颗二元查找树,将该树转 ...

  6. c语言中fact函数怎么调用,C语言程序题: 1、编写一个求n!的函数fact(n),要求fact函数分别用递归和非递归两种方法实现...

    点击查看C语言程序题: 1.编写一个求n!的函数fact(n),要求fact函数分别用递归和非递归两种方法实现具体信息 答:int fac(int n) //非递归{int f=1; for(;n;) ...

  7. c语言求出两个最大素数,求两个正整数的最大公约数      思路:这是一个很基本的问题,最常见的就是两种方法,辗转相除法和辗转相减法。通式分别为 f(x, y) = f(y, x%y...

    求两个正整数的最大公约数 思路:这是一个很基本的问题,最常见的就是两种方法,辗转相除法和辗转相减法.通式分别为 f(x, y) = f(y, x%y), f(x, y) = f(y, x - y) ( ...

  8. Java1.使用二分搜索算法查找任意N个有序数列中的指定元素。 2.通过上机实验进行算法实现。 3.保存和打印出程序的运行结果,并结合程序进行分析,上交实验报告。 4.至少使用两种方法进行编程,直接查

    1.使用二分搜索算法查找任意N个有序数列中的指定元素. 2.通过上机实验进行算法实现. 3.保存和打印出程序的运行结果,并结合程序进行分析,上交实验报告. 4.至少使用两种方法进行编程,直接查找/递归 ...

  9. python的三种取整方式_python 取整的两种方法

    问题简介: 要把一个浮点数(float)整数部分提取出来.比如把"2.1"变成"2"的这一过程:现在我们给这个过程起一个名字叫"取整".那么 ...

最新文章

  1. Python中Queue.get()方法阻塞
  2. 怎么确保一个集合不能被修改?
  3. pytorch实现常用的一些即插即用模块(长期更新)
  4. 基于鸿蒙Hi3861和华为云平台的烟雾报警器(附源码)
  5. php空间 数据库设计,php进阶之数据库设计/ 选择合适的表引擎
  6. 20-21-2网络管理quiz6
  7. primefaces教程_Primefaces面板,PanelGrid和PanelMenu示例教程
  8. DIV+CSS的好处和意义
  9. html在网页中图片打不开,网页图片不显示,教您网页图片不显示如何解决
  10. textpattern 在 nginx 上的 rewrite 规则
  11. python二进制转十进制编程_怎么用python二进制转换十进制
  12. DNS域名解析过程剖析
  13. VMware虚拟机转换为kvm虚拟机
  14. 详谈如何实现手机浏览器跳转微信指定页面加好友及跳转微信公众号一键关注
  15. “当高启强遇到陈书婷”与TCP协议
  16. 硬盘柱面损坏怎么办_硬盘0磁道损坏怎么办
  17. ESP32+DHT11+Arduino连接phpstudy的本地数据库
  18. 【C++IO流】C++打印浮点数小数点后多少的方法,序列化
  19. 必应拼音输入法与搜狗拼音输入法对比评测报告之功能评价篇
  20. 个人作业2——必应词典案件分析

热门文章

  1. usbnet驱动结构
  2. Ubuntu 20.04安装百度拼音输入法
  3. 天河计算机学院,23名90后加入国防科大“天河”超级计算机团队
  4. C语言 | 改变指针变量的值
  5. spring 自定义标签 学习二
  6. 关于widedeep的再思考
  7. PHP用*号替代姓名除第一个字之外的字符
  8. 香港免费空间和美国免费空间需要实名认证吗?
  9. 蓝桥杯第十一届真题:八次求和
  10. url 转pdf工具