当前位置: 首页 > 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轻松地实…...

突破Windows多显示器显示壁垒:SetDPI重新定义显示体验

突破Windows多显示器显示壁垒&#xff1a;SetDPI重新定义显示体验 【免费下载链接】SetDPI 项目地址: https://gitcode.com/gh_mirrors/se/SetDPI 在当今多设备协同工作的时代&#xff0c;显示器已成为我们与数字世界交互的重要窗口。然而&#xff0c;当程序员小李将笔…...

JPEXS Free Flash Decompiler与Web3.0存储:去中心化SWF文件管理的终极指南

JPEXS Free Flash Decompiler与Web3.0存储&#xff1a;去中心化SWF文件管理的终极指南 【免费下载链接】jpexs-decompiler JPEXS Free Flash Decompiler 项目地址: https://gitcode.com/gh_mirrors/jp/jpexs-decompiler JPEXS Free Flash Decompiler是一款功能强大的开源…...

如何通过3个步骤快速掌握BetaFlight黑匣子日志分析

如何通过3个步骤快速掌握BetaFlight黑匣子日志分析 【免费下载链接】blackbox-log-viewer Interactive log viewer for flight logs recorded with blackbox 项目地址: https://gitcode.com/gh_mirrors/bl/blackbox-log-viewer 你是否曾经在调试无人机飞行问题时感到束手…...

Webots仿真实战:如何用C语言控制四轮小车实现自动行驶

Webots仿真实战&#xff1a;C语言控制四轮小车自动行驶全攻略 引言 在机器人开发领域&#xff0c;仿真环境的重要性不言而喻。它不仅能大幅降低硬件成本&#xff0c;还能加速开发周期&#xff0c;让开发者专注于算法和控制逻辑的优化。Webots作为一款专业的机器人仿真软件&…...

三步打造沉浸式AI对话体验:SillyTavern终极指南

三步打造沉浸式AI对话体验&#xff1a;SillyTavern终极指南 【免费下载链接】SillyTavern LLM Frontend for Power Users. 项目地址: https://gitcode.com/GitHub_Trending/si/SillyTavern 你是否厌倦了单调的文字聊天&#xff1f;想让AI助手不仅能"说"&#…...

Cursor+Qt5.12.12开发环境配置全攻略:从插件安装到项目构建

CursorQt5.12.12开发环境配置全攻略&#xff1a;从插件安装到项目构建 对于刚接触Qt开发或从其他IDE迁移到Cursor的开发者来说&#xff0c;配置一个高效的开发环境是首要任务。Qt5.12.12作为长期支持版本(LTS)&#xff0c;在稳定性和兼容性方面表现优异&#xff0c;而Cursor作为…...

3步解锁苹果电脑新玩法:用PlayCover畅玩iOS游戏和应用

3步解锁苹果电脑新玩法&#xff1a;用PlayCover畅玩iOS游戏和应用 【免费下载链接】PlayCover Community fork of PlayCover 项目地址: https://gitcode.com/gh_mirrors/pl/PlayCover 还在羡慕朋友在iPad上玩热门手游&#xff0c;而你的Mac只能干看着&#xff1f;想知道…...

直流电机选型避坑指南:STM32项目为什么推荐TB6612而不是L298N?

STM32直流电机驱动芯片深度对比&#xff1a;TB6612与L298N实战选型指南 在嵌入式开发领域&#xff0c;直流电机驱动方案的选择往往决定了整个项目的稳定性和能效表现。面对市面上众多的驱动芯片&#xff0c;如何根据项目需求做出最优选择&#xff1f;本文将基于实测数据&#x…...

NaViL-9B图文问答入门必看:纯文本+图像理解双模式快速上手

NaViL-9B图文问答入门必看&#xff1a;纯文本图像理解双模式快速上手 1. 认识NaViL-9B多模态模型 NaViL-9B是一款原生支持多模态交互的大语言模型&#xff0c;由专业研究团队开发。它最大的特点是能同时处理纯文本问答和图片内容理解任务&#xff0c;就像一个同时精通文字和视…...

Chatbot Arena排行榜单实战指南:从数据采集到模型优化

Chatbot Arena排行榜单实战指南&#xff1a;从数据采集到模型优化 在构建和优化自己的对话AI时&#xff0c;我们常常面临一个核心问题&#xff1a;如何客观、全面地评估它的性能&#xff1f;闭门造车式的测试往往带有主观偏见&#xff0c;而Chatbot Arena这类公开的排行榜单&a…...