代码随想录算法训练营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. Linux下修改MAC地址总结
  2. 判断一件事有无技术含量的标准
  3. DPDK — DPDK APP 的指令行参数
  4. AngularJS的稍复杂form验证
  5. Java 程序员必备的 Intellij IDEA 插件
  6. [android] 百度地图开发 (二).定位城市位置和城市POI搜索
  7. 尼康d850相机参数测试软件,尼康 - D850 - 产品介绍
  8. 飞鸽传书绿色版 为什么比较多人用?
  9. package.json和package-lock.json的区别
  10. WEB下的excel批量导入功能
  11. leetcode python3 简单题27. Remove Element
  12. 金字塔原理--公开演讲
  13. iOS开发--开发者帐号
  14. UVC系列2-探索Android UVC协议
  15. 小程序与MySQL数据库的交互_微信小程序与服务器的交互原理
  16. Java 实现倒数第一个斜杠和倒数第二个斜杠数据工具类
  17. python 知乎接口_python爬虫入门(3)--利用requests构建知乎API
  18. ARMv8-A架构基础之A64指令
  19. ORA-20011KUP-11024ORA-29913
  20. 【FXCG】海龟交易法的使用方法和注意事项

热门文章

  1. JS逆向加密——美团店铺详情_token参数
  2. 数据库范式(normalization)
  3. Win系统 - 单通道 16G 内存 VS 双通道 16G 内存
  4. ubuntu 100M 到 10M
  5. 坐标轴删了怎么恢复_EXCEL表折线图已经删掉的图例怎么恢复 - 卡饭网
  6. 高德地图API和百度地图API哪个更适合开发者?
  7. USB-HOST、USB-DEVICE、USB-OTG
  8. 一个80年小子的创业道理,和所有准备创业或者正在创业的兄弟们共享
  9. 长航安庆警方成功破获系列非法经营“笑气”案
  10. W3150A+评估板--EVB-PIC24用户手册(四)硬件设计指南