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

leetcode刷题记录:hot100强化训练2:二叉树+图论

二叉树

36. 二叉树的中序遍历

递归就不写了,写一下迭代法

class Solution(object):def inorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""if not root:return res = []cur = rootstack = []while cur or stack:if cur:stack.append(cur)cur = cur.left                else:cur = stack.pop()res.append(cur.val)cur = cur.rightreturn res

顺便再写一下前序和后序的迭代法
前序:

class Solution(object):def preorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""if not root:returnst = [root]res = []# cur = while st:cur = st.pop()res.append(cur.val)            if cur.right:st.append(cur.right)if cur.left:st.append(cur.left)return res

后序:

class Solution(object):def postorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""if not root:returncur = rootst = []prev = Noneres = []while st or cur:if cur:st.append(cur)cur = cur.leftelse:cur = st.pop()#现在需要确定的是是否有右子树,或者右子树是否访问过#如果没有右子树,或者右子树访问完了,也就是上一个访问的节点是右子节点时#说明可以访问当前节点if not cur.right or cur.right == prev:res.append(cur.val)prev = curcur = Noneelse:st.append(cur)cur = cur.right                    return res

37. 二叉树的最大深度

分解很简单,直接交给递归函数。但是遍历的思路都要会

  1. 分解(动态规划思路)
class Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""if not root:return 0return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
  1. 遍历(回溯思路)
    走完之后depth-1
class Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""def helper(root):if not root:self.res = max(self.res, self.depth)returnself.depth += 1helper(root.left)                                helper(root.right)               self.depth -= 1self.depth = 0self.res = 0helper(root)return self.res
  1. 延伸:可否不用递归来做这道题?
    这个解法是chatgpt写的,将depth和node一起压入栈,避免对depth +1, -1的操作
class Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""if not root:return 0stack = [(root, 1)]max_depth = 0while stack:node, depth = stack.pop()if node:max_depth = max(max_depth, depth)if node.right:stack.append((node.right, depth + 1))if node.left:stack.append((node.left, depth + 1))        return max_depth
  1. 反转二叉树
    递归函数的定义:给定二叉树根节点,反转它的左右子树。
    后续位置递归
class Solution(object):def invertTree(self, root):""":type root: TreeNode:rtype: TreeNode"""if not root:returnself.invertTree(root.left) self.invertTree(root.right) root.left, root.right = root.right, root.leftreturn root
  1. 对称二叉树
    核心思路:
    如果一个树的左子树与右子树镜像对称,那么这个树是对称的。该问题可以转化为:两个树在什么情况下互为镜像?
    如果同时满足下面的条件,两个树互为镜像:
  2. 它们的两个根结点具有相同的值
  3. 每个树的右子树都与另一个树的左子树镜像对称

创建一个函数,传入2个节点,判断是否对称

class Solution(object):def isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""def check(p, q):if p and q:a = p.val == q.valb = check(p.left, q.right)c = check(p.right, q.left)return a and b and celif (not p) and (not q):return Trueelse:return Falsereturn check(root, root)

40 二叉树的直径

class Solution(object):def diameterOfBinaryTree(self, root):""":type root: TreeNode:rtype: int"""def helper(root):if not root:return 0l = helper(root.left)r = helper(root.right)d = max(l, r)  + 1self.res = max(self.res, l + r)return dself.res = 0helper(root)return self.res     

41. 二叉树的层序遍历

class Solution(object):def levelOrder(self, root):""":type root: TreeNode:rtype: List[List[int]]"""if not root:returnq = [root]res = []while q:sz = len(q)temp = []for i in range(sz):cur = q.pop(0)temp.append(cur.val)if cur.left:q.append(cur.left)if cur.right:q.append(cur.right)res.append(temp[:])return res

42. 构造二叉搜索树

有序数组,找到mid,nums[mid]是根节点,左边和右边分别是左子树和右子树

class Solution(object):def sortedArrayToBST(self, nums):""":type nums: List[int]:rtype: TreeNode"""def construct(nums, lo, hi):if lo > hi:returnmid = lo + (hi-lo)//2root = TreeNode(nums[mid])root.left = construct(nums, lo, mid-1)root.right = construct(nums, mid+1, hi)return rootif not nums:returnn = len(nums)return construct(nums, 0, n-1)

43. 判断二叉搜索树

迭代法写中序遍历

class Solution(object):def isValidBST(self, root):""":type root: TreeNode:rtype: bool"""if not root:return Trueprev = Nonest = []cur = rootwhile st or cur:if cur:st.append(cur)cur = cur.leftelse:cur = st.pop()                if prev and prev.val >= cur.val:                    return Falseprev = curcur = cur.rightreturn True

44. bst第k小元素

迭代法遍历,太爽了

class Solution(object):def kthSmallest(self, root, k):""":type root: TreeNode:type k: int:rtype: int"""st = []cur = rooti = 0while st or cur:if cur:st.append(cur)cur = cur.leftelse:cur = st.pop()i += 1if i == k:return cur.valcur = cur.right          

45. 二叉树的右视图

层序遍历,从右往左

class Solution(object):def rightSideView(self, root):""":type root: TreeNode:rtype: List[int]"""if not root:returnq = deque()q.append(root)res = []while q:sz = len(q)res.append(q[0].val)for i in range(sz):cur = q.popleft()if cur.right:q.append(cur.right)if cur.left:q.append(cur.left)return res

46. 二叉树展开为链表

class Solution(object):def flatten(self, root):""":type root: TreeNode:rtype: None Do not return anything, modify root in-place instead."""if not root:returnl = self.flatten(root.left)r = self.flatten(root.right)    root.left = Noneroot.right = lnode = rootwhile node.right:node = node.rightnode.right = rreturn root

47. 从前序和中序构造二叉树

class Solution(object):def buildTree(self, preorder, inorder):""":type preorder: List[int]:type inorder: List[int]:rtype: TreeNode"""def helper(preorder, prelo, prehi, inorder, inlo, inhi):if prelo > prehi or inlo > inhi:returnroot_val = preorder[prelo] root_idx = inorder.index(root_val)left_size = root_idx - inloroot = TreeNode(root_val)root.left = helper(preorder, prelo+1, prelo+left_size, inorder, inlo, root_idx-1)root.right = helper(preorder, prelo+left_size+1, prehi, inorder, root_idx+1, inhi)return rootn = len(preorder)return helper(preorder, 0, n-1, inorder, 0, n-1)

48. 路径总和III

后序遍历,helper返回以root为开始的路径和的哈希表

class Solution(object):def pathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: int"""def helper(root):if not root:return {}l = helper(root.left)r = helper(root.right)res = {}for k, v in l.items():x = root.val + kres[x] = v              for k, v in r.items():x = root.val + kres[x] = res.get(x, 0) + vres[root.val] = res.get(root.val, 0) + 1self.cnt += res.get(targetSum, 0)return resself.cnt = 0x = helper(root)        return self.cnt

49. 二叉树的最近公共祖先

思路:如果一个节点能够在它的左右子树中分别找到 p 和 q,则该节点为 LCA 节点。

class Solution(object):def lowestCommonAncestor(self, root, p, q):""":type root: TreeNode:type p: TreeNode:type q: TreeNode:rtype: TreeNode"""def helper(root, p, q):if not root:return# 说明p或者q本身就是LCAif root == p or root == q:return rootleft = helper(root.left, p, q)right = helper(root.right, p, q)   if left and right:# 说明p和q一个在左子树,另一个在右子树,root就是LCAreturn rootreturn left if left else right     return helper(root, p, q)

50. 二叉树的最大路径和

自己ac的hard题目。

class Solution(object):def maxPathSum(self, root):""":type root: TreeNode:rtype: int"""def helper(root):if not root:return 0leftMax = helper(root.left)rightMax = helper(root.right)x = max(root.val, root.val+leftMax, root.val+rightMax)            self.res = max(self.res, x, root.val+leftMax+rightMax)return xself.res = -1001helper(root)return self.res

图论

51. 岛屿数量

dfs

class Solution(object):def numIslands(self, grid):""":type grid: List[List[str]]:rtype: int"""def dfs(grid, i, j):m, n = len(grid), len(grid[0])if i < 0 or i >= m or j < 0 or j >= n:return                 if grid[i][j] == "0":return grid[i][j] = "0"dfs(grid, i+1, j)dfs(grid, i-1, j)dfs(grid, i, j+1)dfs(grid, i, j-1)m, n = len(grid), len(grid[0])res = 0for i in range(m):for j in range(n):if grid[i][j] == "1":dfs(grid, i, j)res += 1return res

52 腐烂橘子

来自 作者:nettee的题解
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。翻译一下,实际上就是求腐烂橘子到所有新鲜橘子的最短路径。要用bfs
一开始,我们找出所有腐烂的橘子,将它们放入队列,作为第 0 层的结点。
然后进行 BFS 遍历,每个结点的相邻结点可能是上、下、左、右四个方向的结点,注意判断结点位于网格边界的特殊情况。
由于可能存在无法被污染的橘子,我们需要记录新鲜橘子的数量。在 BFS 中,每遍历到一个橘子(污染了一个橘子),就将新鲜橘子的数量减一。如果 BFS 结束后这个数量仍未减为零,说明存在无法被污染的橘子

class Solution(object):def orangesRotting(self, grid):""":type grid: List[List[int]]:rtype: int"""       m, n = len(grid), len(grid[0])q = deque()fresh_cnt = 0for i in range(m):for j in range(n):if grid[i][j] == 1:fresh_cnt += 1elif grid[i][j] == 2:q.append((i, j))res = 0while fresh_cnt > 0  and q:res += 1sz = len(q)for i in range(sz):cur = q.popleft()i, j = cur[0], cur[1]if i > 0 and grid[i-1][j] == 1:q.append((i-1, j))grid[i-1][j] = 2fresh_cnt -= 1 if i < m-1 and grid[i+1][j] == 1:q.append((i+1, j))grid[i+1][j] = 2fresh_cnt -= 1 if j > 0 and grid[i][j-1] == 1:q.append((i, j-1))grid[i][j-1] = 2fresh_cnt -= 1 if j < n-1 and grid[i][j+1] == 1:q.append((i, j+1))grid[i][j+1] = 2fresh_cnt -= 1     if fresh_cnt == 0:return reselse:return -1

53. 课程表

自己写的暴力解法:

class Solution(object):def canFinish(self, numCourses, prerequisites):""":type numCourses: int:type prerequisites: List[List[int]]:rtype: bool"""d = {}for i in prerequisites:a, b = i[0], i[1]if a not in d:d[a] = [b]else:d[a].append(b)learned = set()while len(learned) < numCourses:L = len(learned)# print(learned, x)for n in range(numCourses):if n not in d:learned.add(n)else:flag = Truefor x in d[n]:if x not in learned: flag = Falsebreakif flag:learned.add(n)# print(learned, x)if len(learned) == L:return Falsereturn True                

看题解:有向图+bfs。用一个in_degree数组存储每个节点(每节课)的入度,再用一个map d存储每个节点的出度。
每次入度为0的课程入队,bfs的思路。

class Solution(object):def canFinish(self, numCourses, prerequisites):""":type numCourses: int:type prerequisites: List[List[int]]:rtype: bool"""d = {}in_degree = [0] * numCoursesfor i in prerequisites:            a, b = i[0], i[1]in_degree[a] += 1if b not in d:d[b] = [a]else:d[b].append(a)q = deque()for n in range(numCourses):if in_degree[n] == 0:q.append(n)cnt = 0while q:cur = q.popleft()cnt += 1if cur in d:for k in d[cur]:in_degree[k] -= 1if in_degree[k] == 0:q.append(k)return cnt == numCourses

54. Trie前缀树

面试大概率不会考,跳过

相关文章:

leetcode刷题记录:hot100强化训练2:二叉树+图论

二叉树 36. 二叉树的中序遍历 递归就不写了&#xff0c;写一下迭代法 class Solution(object):def inorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""if not root:return res []cur rootstack []while cur or st…...

湘潭大学信息与网络安全复习笔记2(总览)

前面的实验和作业反正已经结束了&#xff0c;现在就是集中火力把剩下的内容复习一遍&#xff0c;这一篇博客的内容主要是参考教学大纲和教学日历 文章目录 教学日历教学大纲 教学日历 总共 12 次课&#xff0c;第一次课是概述&#xff0c;第二次和第三次课是密码学基础&#x…...

C语言:头歌使用函数找出数组中的最大值

任务描述 本关任务&#xff1a;本题要求实现一个找出整型数组中最大值的函数。 函数接口定义&#xff1a; int FindArrayMax( int a[], int n ); 其中a是用户传入的数组&#xff0c;n是数组a中元素的个数。函数返回数组a中的最大值。 主程序样例: #include <stdio.h>#…...

【技巧】Leetcode 191. 位1的个数【简单】

位1的个数 编写一个函数&#xff0c;输入是一个无符号整数&#xff08;以二进制串的形式&#xff09;&#xff0c;返回其二进制表达式中 设置位 的个数&#xff08;也被称为汉明重量&#xff09;。 示例 1&#xff1a; 输入&#xff1a;n 11 输出&#xff1a;3 解释&#x…...

【Pandas驯化-02】pd.read_csv读取中文出现error解决方法

【Pandas】驯化-02pd.read_csv读取中文出现error解决方法 本次修炼方法请往下查看 &#x1f308; 欢迎莅临我的个人主页 &#x1f448;这里是我工作、学习、实践 IT领域、真诚分享 踩坑集合&#xff0c;智慧小天地&#xff01; &#x1f387; 相关内容文档获取 微信公众号 &…...

linux下C语言如何操作文件(三)

我们继续介绍file_util.c中的函数: bool create_dir(const char* path):创建目录,根据给定的path创建目录,成功返回true,否则返回false。如果有父目录不存在,该函数不会创建。 /*** 创建目录* @param path 目录路径* @return true 创建成功,false 创建失败*/ bool cre…...

6.14作业

使用手动连接&#xff0c;将登录框中的取消按钮使用第二中连接方式&#xff0c;右击转到槽&#xff0c;在该槽函数中&#xff0c;调用关闭函数 将登录按钮使用qt4版本的连接到自定义的槽函数中&#xff0c;在槽函数中判断ui界面上输入的账号是否为"admin"&#xff0…...

MySQL数据库管理(一)

目录 1.MySQL数据库管理 1.1 常用的数据类型​编辑 1.2 char和varchar区别 2. 增删改查命令操作 2.1 查看数据库结构 2.2 SQL语言 2.3 创建及删除数据库和表 2.4 管理表中的数据记录 2.5 修改表名和表结构 3.MySQL的6大约束属性 1.MySQL数据库管理 1.1 常用的数据类…...

Kafka使用教程和案例详解

Kafka 使用教程和案例详解 Kafka 使用教程和案例详解1. Kafka 基本概念1.1 Kafka 是什么?1.2 核心组件2. Kafka 安装与配置2.1 安装 Kafka使用包管理器(如 yum)安装使用 Docker 安装2.2 配置 Kafka2.3 启动 Kafka3. Kafka 使用教程3.1 创建主题3.2 生产消息3.3 消费消息3.4 …...

TGI模型- 同期群-评论文本

用户偏好分析 TGI 1.1 用户偏好分析介绍 要分析的目标&#xff0c;在目标群体中的均值 和 全部群体里的均值进行比较&#xff0c; 差的越多说明 目标群体偏好越明显 TGI&#xff08;Target Group Index&#xff0c;目标群体指数&#xff09;用于反映目标群体在特定研究范围内…...

ESP32 BLE学习(0) — 基础架构

前言 &#xff08;1&#xff09;学习本文之前&#xff0c;需要先了解一下蓝牙的基本概念&#xff1a;BLE学习笔记&#xff08;0.0&#xff09; —— 基础概念&#xff08;0&#xff09; &#xff08;2&#xff09; 学习一款芯片的蓝牙肯定需要先简单了解一下该芯片的体系结构&a…...

【JAVA】Java中Spring Boot如何设置全局的BusinessException

文章目录 前言一、函数解释二、代码实现三、总结 前言 在Java应用开发中&#xff0c;我们常常需要读取配置文件。Spring Boot提供了一种方便的方式来读取配置。在本文中&#xff0c;我们将探讨如何在Spring Boot中使用Value和ConfigurationProperties注解来读取配置。 一、函数…...

pdf.js实现web h5预览pdf文件(兼容低版本浏览器)

注意 使用的是pdf.js 版本为 v2.16.105。因为新版本 兼容性不太好&#xff0c;部分手机预览不了&#xff0c;所以采用v2版本。 相关依赖 "canvas": "^2.11.2", "pdfjs-dist": "^2.16.105", "core-js-pure": "^3.37.…...

SSID简介

一、 SSID 概念定义 SSID&#xff08;Service Set Identifier&#xff09;即服务集标识符。它是无线网络中的一个重要标识&#xff0c;用于区分不同的无线网络。 相当于无线网络的名称&#xff0c;用于区分不同的无线网络。用户在众多可用网络中识别和选择特定网络的依据。通…...

PS通过GTX实现SFP网络通信1

将 PS ENET1 的 GMII 接口和 MDIO 接口 通过 EMIO 方 式引出。在 PL 端将引出的 GMII 接口和 MDIO 接口与 IP 核 1G/2.5G Ethernet PCS/PMA or SGMII 连接&#xff0c; 1G/2.5G Ethernet PCS/PMA or SGMII 通过高速串行收发器 GTX 与 MIZ7035/7100 开发…...

前端面试项目细节重难点(已工作|做分享)(九)

面试官&#xff1a;请你讲讲你在工作中如何开发一个新需求&#xff0c;你的整个开发过程是什么样的&#xff1f; 答&#xff1a;仔细想想&#xff0c;我开发新需求的过程如下&#xff1a; &#xff08;1&#xff09;第一步&#xff1a;理解需求文档&#xff1a; 首先&#x…...

区间预测 | Matlab实现BP-ABKDE的BP神经网络自适应带宽核密度估计多变量回归区间预测

区间预测 | Matlab实现BP-ABKDE的BP神经网络自适应带宽核密度估计多变量回归区间预测 目录 区间预测 | Matlab实现BP-ABKDE的BP神经网络自适应带宽核密度估计多变量回归区间预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.Matlab实现BP-ABKDE的BP神经网络自适应带…...

抢占人工智能行业红利,前阿里巴巴产品专家带你15天入门AI产品经理

前言 当互联网行业巨头纷纷布局人工智能&#xff0c;国家将人工智能上升为国家战略&#xff0c;藤校核心课程涉足人工智能…人工智能领域蕴含着巨大潜力&#xff0c;早已成为业内共识。 面对极大的行业空缺&#xff0c;不少人都希望能抢占行业红利期&#xff0c;进入AI领域。…...

MEMS:Lecture 16 Gyros

陀螺仪原理 A classic spinning gyroscope measures the rotation rate by utilizing the conservation of angular momentum. 经典旋转陀螺仪通过利用角动量守恒来测量旋转速率。 Coriolis Effect and Coriolis Force 科里奥利效应是一种出现在旋转参考系中的现象。它描述了…...

Java中List流式转换为Map的终极指南

哈喽&#xff0c;大家好&#xff0c;我是木头左&#xff01; 在Java编程中&#xff0c;经常需要将一个List对象转换为另一个Map对象。这可能是因为需要根据List中的元素的某些属性来创建一个新的键值对集合。在本文中&#xff0c;我将向您展示如何使用Java 中的流式API轻松地实…...

设计模式和设计原则回顾

设计模式和设计原则回顾 23种设计模式是设计原则的完美体现,设计原则设计原则是设计模式的理论基石, 设计模式 在经典的设计模式分类中(如《设计模式:可复用面向对象软件的基础》一书中),总共有23种设计模式,分为三大类: 一、创建型模式(5种) 1. 单例模式(Sing…...

23-Oracle 23 ai 区块链表(Blockchain Table)

小伙伴有没有在金融强合规的领域中遇见&#xff0c;必须要保持数据不可变&#xff0c;管理员都无法修改和留痕的要求。比如医疗的电子病历中&#xff0c;影像检查检验结果不可篡改行的&#xff0c;药品追溯过程中数据只可插入无法删除的特性需求&#xff1b;登录日志、修改日志…...

cf2117E

原题链接&#xff1a;https://codeforces.com/contest/2117/problem/E 题目背景&#xff1a; 给定两个数组a,b&#xff0c;可以执行多次以下操作&#xff1a;选择 i (1 < i < n - 1)&#xff0c;并设置 或&#xff0c;也可以在执行上述操作前执行一次删除任意 和 。求…...

spring:实例工厂方法获取bean

spring处理使用静态工厂方法获取bean实例&#xff0c;也可以通过实例工厂方法获取bean实例。 实例工厂方法步骤如下&#xff1a; 定义实例工厂类&#xff08;Java代码&#xff09;&#xff0c;定义实例工厂&#xff08;xml&#xff09;&#xff0c;定义调用实例工厂&#xff…...

令牌桶 滑动窗口->限流 分布式信号量->限并发的原理 lua脚本分析介绍

文章目录 前言限流限制并发的实际理解限流令牌桶代码实现结果分析令牌桶lua的模拟实现原理总结&#xff1a; 滑动窗口代码实现结果分析lua脚本原理解析 限并发分布式信号量代码实现结果分析lua脚本实现原理 双注解去实现限流 并发结果分析&#xff1a; 实际业务去理解体会统一注…...

《基于Apache Flink的流处理》笔记

思维导图 1-3 章 4-7章 8-11 章 参考资料 源码&#xff1a; https://github.com/streaming-with-flink 博客 https://flink.apache.org/bloghttps://www.ververica.com/blog 聚会及会议 https://flink-forward.orghttps://www.meetup.com/topics/apache-flink https://n…...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

10-Oracle 23 ai Vector Search 概述和参数

一、Oracle AI Vector Search 概述 企业和个人都在尝试各种AI&#xff0c;使用客户端或是内部自己搭建集成大模型的终端&#xff0c;加速与大型语言模型&#xff08;LLM&#xff09;的结合&#xff0c;同时使用检索增强生成&#xff08;Retrieval Augmented Generation &#…...

安宝特案例丨Vuzix AR智能眼镜集成专业软件,助力卢森堡医院药房转型,赢得辉瑞创新奖

在Vuzix M400 AR智能眼镜的助力下&#xff0c;卢森堡罗伯特舒曼医院&#xff08;the Robert Schuman Hospitals, HRS&#xff09;凭借在无菌制剂生产流程中引入增强现实技术&#xff08;AR&#xff09;创新项目&#xff0c;荣获了2024年6月7日由卢森堡医院药剂师协会&#xff0…...

Windows安装Miniconda

一、下载 https://www.anaconda.com/download/success 二、安装 三、配置镜像源 Anaconda/Miniconda pip 配置清华镜像源_anaconda配置清华源-CSDN博客 四、常用操作命令 Anaconda/Miniconda 基本操作命令_miniconda创建环境命令-CSDN博客...