【LeetCode】113. Path Sum II 路径总和 II 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/
题目地址:https://leetcode.com/problems/path-sum-ii/description/
题目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
题目大意
在一棵二叉树中,找出从根节点到叶子节点的和为target的所有路径。
解题方法
二叉树问题大多都可以用递归和迭代的方法求解。本题也是如此。
左边是BFS,按照层进行搜索;图右边是DFS,先一路走到底,然后再回头搜索。
BFS
BFS使用队列,把每个还没有搜索到的点依次放入队列,然后再弹出队列的头部元素当做当前遍历点。BFS总共有两个模板:
- 如果不需要确定当前遍历到了哪一层,BFS模板如下。
while queue 不空:
cur = queue.pop()
if cur 有效且未被访问过:
进行处理
for 节点 in cur 的所有相邻节点:
if 该节点有效:
queue.push(该节点)
- 如果要确定当前遍历到了哪一层,BFS模板如下。
这里增加了level表示当前遍历到二叉树中的哪一层了,也可以理解为在一个图中,现在已经走了多少步了。size表示在当前遍历层有多少个元素,也就是队列中的元素数,我们把这些元素一次性遍历完,即把当前层的所有元素都向外走了一步。
level = 0
while queue 不空:
size = queue.size()
while (size --) {
cur = queue.pop()
if cur 有效且未被访问过:
进行处理
for 节点 in cur的所有相邻节点:
if 该节点有效:
queue.push(该节点)
}
level ++;
上面两个是通用模板,在任何题目中都可以用,是要记住的!
本题要求所有的路径,不需要按层遍历,因此使用模板一。(注:模板二的使用见102. 二叉树的层序遍历)
代码如下,使用队列,同时保存(将要处理的节点,路径,路径和)
,这样在访问一个节点的时候,就能知道已有的路径和「路径和」。如果当前节点是叶子节点并且,已有的「路径和」加上当前叶子的值等于sum
,说明找到了一条满足题意的路径,放入结果 res 中。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
que = deque()
que.append((root, [], 0)) # 将要处理的节点,路径,路径和
while que:
node, path, pathSum = que.popleft()
if not node: # 如果是空节点,不处理
continue
if not node.left and not node.right: # 如果是叶子节点
if node.val + pathSum == sum: # 加上叶子节点后,路径和等于sum
res.append(path + [node.val]) # 保存路径
# 处理左子树
que.append((node.left, path + [node.val], pathSum + node.val))
# 处理右子树
que.append((node.right, path + [node.val], pathSum + node.val))
return res
DFS
题目要求二叉树中从根节点到叶子节点的「路径和」为 sum 的所有路径。
我们必须使用一个变量 res 保存最终的所有路径结果,用一个变量 path 保存每条路径。另外需要记录路径和,我们反其道而行之,记录到达每个节点时的sum - 「路径和」
;如果遍历到叶子节点的时候,sum - 「路径和」
恰好等于叶子节点的值,那么这条从根节点到叶子节点的路径即为一条满足题目的路径。
在下面的代码中,res 变量从头到尾只有同一个,但是每次调用 dfs() 函数的时候 path 变量都是不同的。Python 中,path + [root.val]
会生成一个新的列表,因此所有的递归函数的里面的 path 操作不会互相干扰。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
self.dfs(root, sum, res, [])
return res
def dfs(self, root, sum, res, path):
if not root: # 空节点,不做处理
return
if not root.left and not root.right: # 叶子节点
if sum == root.val: # 剩余的「路径和」恰好等于叶子节点值
res.append(path + [root.val]) # 把该路径放入结果中
self.dfs(root.left, sum - root.val, res, path + [root.val]) # 左子树
self.dfs(root.right, sum - root.val, res, path + [root.val]) # 右子树
日期
2018 年 6 月 22 日 ———— 这周的糟心事终于完了
【LeetCode】113. Path Sum II 路径总和 II 解题报告(Python)的更多相关文章
- [LeetCode] 113. Path Sum II 路径和 II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] 437. Path Sum III 路径和 III
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)
[LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...
- LeetCode 113. Path Sum II路径总和 II (C++)
题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...
- [LeetCode] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)
LeetCode 二叉树路径问题 Path SUM(①②③)总结 Path Sum II leetcode java 描述 Given a binary tree and a sum, find al ...
- 113 Path Sum II 路径总和 II
给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径.例如,给定下面的二叉树和 sum = 22, 5 / \ 4 ...
- [LeetCode] 113. Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- leetcode 113. Path Sum II (路径和) 解题思路和方法
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [leetcode] 113. Path Sum II (Medium)
原题链接 子母题 112 Path Sum 跟112多了一点就是保存路径 依然用dfs,多了两个vector保存路径 Runtime: 16 ms, faster than 16.09% of C++ ...
随机推荐
- Linux— 查看系统的位数
[root@zf-test-web01-4 ~]# file /bin/ls #"/bin/ls" is a binary file /bin/ls: ELF ...
- Linux— rpm 命令
rpm命令是RPM软件包的管理工具.rpm原本是Red Hat Linux发行版专门用来管理Linux各项套件的程序,由于它遵循GPL规则且功能强大方便,因而广受欢迎.逐渐受到其他发行版的采用.RPM ...
- 日常Java 2021/11/15
Applet类 每一个Applet都是java.applet Applet类的子类,基础的Applet类提供了供衍生类调用的方法,以此来得到浏览器上下文的信息和服务.这些方法做了如下事情: 得到App ...
- Hive(十二)【调优】
目录 1.Fetch抓取 2.本地模式 3.表的优化 3.1大小表join 3.2大表Join大表 3.3map join 3.4group By 3.5 count(distinct) 3.6笛卡尔 ...
- Shell变量与算术运算
区分两个 Shell Shell 语言与 Shell 解释器 Shell 语言 写 Shell 脚本使用的是 Shell 语言,Shell 既是一种命令语言,又是一种程序设计语言. 作为命令语言,它交 ...
- Linux基础命令---ntpq查询时间服务器
ntpq ntpq指令使用NTP模式6数据包与NTP服务器通信,能够在允许的网络上查询的兼容的服务器.它以交互模式运行,或者通过命令行参数运行. 此命令的适用范围:RedHat.RHEL.Ubuntu ...
- OkHttp3 使用
导入 compile 'com.squareup.okhttp3:okhttp:3.3.0' GET请求 String url = "https://www.baidu.com/" ...
- Linux基础命令---mget获取ftp文件
mget 使用lftp登录mftp服务器之后,可以使用mget指令从服务器获取文件.mget指令可以使用通配符,而get指令则不可以. 1.语法 mget [-E] [-a] [- ...
- 『学了就忘』Linux系统管理 — 83、Linux中进程的查看(top命令)
目录 1.top命令介绍 2.top命令示例 3.top命令输出项解释 4.top命令常用的实例 1.top命令介绍 top命令是用来动态显示系统中进程的命令. [root@localhost ~]# ...
- MySQL 面试题汇总(持续更新中)
COUNT COUNT(*) 和 COUNT(1) 根据 MySQL 官方文档的描述: InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) opera ...